几种在springboot启动类之前做某些操作的方法

第一种方法:

使用 @PostConstruct注解

 1 @Configuration
 2 
 3 public class Test1 {
 4 
 5     @Autowired
 6 
 7     private Environment environment;
 8 
 9     @PostConstruct
10 
11     public void test(){
12 
13         String property = environment.getProperty("aaa.bbb");
14 
15         System.out.println("test1"+property);
16 
17     }
18 
19 }

 

第二种方法:

实现InitializingBean接口

 1 @Configuration
 2 
 3 public class Test2 implements InitializingBean {
 4 
 5     @Autowired
 6 
 7     private Environment environment;
 8 
 9     @Override
10 
11     public void afterPropertiesSet() throws Exception {
12 
13         String property = environment.getProperty("aaa.bbb");
14 
15         System.out.println("test2"+property);
16 
17     }
18 
19 }

 

第三种方法:

实现BeanPostProcessor接口

 1 @Configuration
 2 
 3 public class Test3 implements BeanPostProcessor {
 4 
 5     @Autowired
 6 
 7     private Environment environment;
 8 
 9     @Override
10 
11     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
12 
13         String property = environment.getProperty("aaa.bbb");
14 
15         System.out.println("test3"+property);
16 
17         return bean;
18 
19     }
20 
21     @Override
22 
23     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
24 
25         return bean;
26 
27     }
28 
29 }

 

第四种方法:

直接在启动类之前做操作,这种方法不推荐。

运行优先级为:启动类前->BeanPostProcessor->@PostConstruct->InitializingBean

 1 @SpringBootApplication
 2 
 3 public class DemoApplication {
 4 
 5     public static void main(String[] args) {
 6 
 7         System.out.println("test4");
 8 
 9         SpringApplication.run(DemoApplication.class, args);
10 
11     }
12 
13 }

 

上一篇:翻译 - ASP.NET Core 基本知识 - 环境(Environments)


下一篇:Locust压力测试方法