![07628bcb054e669462777cfc0620cccb.png](https://img-blog.csdnimg.cn/img_convert/07628bcb054e669462777cfc0620cccb.png)
我们经常会在项目启动的时候或者某个bean加载之后进行特殊处理, 比如加载配置文件, 配置spring bean, 启动其他容器等等.这里我们总结了spring常用的一些初始化启动方式
spring bean 初始化后启动
- 重写spring bean 无参构造器
spring 加载 初始化bean也是通过无参构造器实现的, 我们可以重写无参构造器, 实现初始化bean时执行.@Componentpublic class InitBeanDemo0 { public InitBeanDemo0() { System.out.println("加载了配置文件 ... "); }}方法简单, 不过用的不多
- 实现InitializingBean接口
实现 InitializingBean 接口, 重写 afterPropertiesSet方法@Componentpublic class InitBeanDemo1 implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("加载了配置文件 ..."); }}此方式简单比较常用
- 使用注解@PostConstruct
在spring bean中, 需要执行的方法上加该注解@Componentpublic class InitBeanDemo2 { @PostConstruct public void postConstruct() { System.out.println("加载了配置文件 ..."); }}此方式简单比较常用
- 使用Java配置
bean对象public class InitBeanDemo3 { public void init() { System.out.println("InitBeanDemo3 init start ..."); }}配置类@Configurationpublic class InitBeanConfiguration { @Bean(initMethod = "init") public InitBeanDemo3 initBeanDemo3() { return new InitBeanDemo3(); }}Java配置更灵活更强大些, 这里只是使用他的初始化执行方式.
spring 容器初始化后启动
除了上面介绍的那些, 还有一些是和spring容器相关, 不需要和某个spring bean绑定, 就可以用到如下方式
- 实现ApplicationListener接口
实现ApplicationListener接口, 重写 onApplicationEvent方法@Componentpublic class StartupListener implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { System.out.println("ApplicationListener onApplicationEvent start ..."); }}能够监听容器启动情况
![b848b073318f349db0eaf76376d0bfec.png](https://img-blog.csdnimg.cn/img_convert/b848b073318f349db0eaf76376d0bfec.png)
除此之外, spring boot 也提供了两个接口
ApplicationRunner和CommandLineRunner@Componentpublic class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("MyApplicationRunner run start ..." + JSON.toJSONString(args.getNonOptionArgs())); }}@Componentpublic class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("MyCommandLineRunner run start ..." + JSON.toJSONString(args)); }}两者基本相同, 只是重写方法入参不一样, 一个是获取命令行参数对象, 一个是获取命令行原始参数