【SpringBoot】启动前执行的几种方式
程序员文章站
2022-07-15 14:21:18
...
如果饿了就吃,困了就睡,渴了就喝,人生就太无趣了
源码地址:https://github.com/keer123456789/springbootstudy/tree/master/befor_run_demo
第一种:@PostConstruct
@Configuration
public class MyConfig_1 {
@PostConstruct
public void test() {
System.out.println("===================Service 1====================");
}
}
启动运行项目:
第二种 实现InitializingBean接口
@Configuration
public class MyConfig_2 implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("===================Service 2====================");
}
}
启动运行项目:
第三种 实现BeanPostProcessor接口
@Configuration
public class MyConfig_3 implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("===================Service 3====================");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
启动运行项目:(目前输出多次的Service3,每太搞清楚,欢迎指导,会继续学习)
第四种 在启动类run之前执行方法
这种方法不太可取!
@SpringBootApplication
public class BeforRunDemoApplication {
public static void main(String[] args) {
System.out.println("===================Service 5====================");
SpringApplication.run(BeforRunDemoApplication.class, args);
}
}
启动项目:
四种方式的启动顺序
启动类前->BeanPostProcessor->@PostConstruct->InitializingBean
值得注意的是第三种方式,他可以让实现类里的方法提前执行
@Configuration
public class MyConfig_1 {
@PostConstruct
public void test() {
System.out.println("===================Service 1====================");
}
}
@Configuration
public class MyConfig_4 implements BeanPostProcessor {
@PostConstruct
public void test(){
System.out.println("===================Service 4====================");
}
}
启动项目: