在Spring 环境下,一般可以用下面的方法来执行一些系统初始化工作。在spring boot环境下,则可以参考另外一篇文章
https://blog.csdn.net/bigtree_3721/article/details/88431175
A: 通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法。
Spring中InitializingBean接口类为bean提供了定义初始化方法的方式,它仅仅包含一个方法:afterPropertiesSet()。
Bean实现这个接口,在afterPropertiesSet()中编写初始化代码。
B: 通过 <bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法。
总结:
- spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用
- 实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖
- 先调用afterPropertiesSet,再执行 init-method 方法,如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。
C:在指定方法上加上@PostConstruct 或@PreDestroy注解来指定该方法是在初始化之后还是销毁之前调用。
总结:
- spring bean的初始化执行顺序:构造方法 -->
@PostConstruct
注解的方法 -->afterPropertiesSet
方法 -->init-method
指定的方法。 afterPropertiesSet
通过接口实现方式调用(效率上高一点),@PostConstruct
和init-method
都是通过反射机制调用
D:自定义 org.springframework.beans.factory.config.BeanPostProcessor ,来让 spring 回调我们的方法来参与 bean的生命周期
3. @PostConstruct和@PreDestory可以通过在类方法上注解方式实现类似的功能。
例子代码
@Slf4j
public class InitSequenceBean implements InitializingBean {
public InitSequenceBean() {
log.info("InitSequenceBean: construct");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("InitSequenceBean: afterPropertiesSet");
}
@PostConstruct
public void postConstruct() {
log.info("InitSequenceBean: postConstruct");
}
public void initMethod() {
log.info("InitSequenceBean: initMethod");
}
}
@Configuration
public class SystemConfig {
@Bean(initMethod = "initMethod", name = "initSequenceBean")
public InitSequenceBean initSequenceBean() {
return new InitSequenceBean();
}
}
@Slf4j
public class InitSequenceBeanTest extends ApplicationTests {
@Autowired
private InitSequenceBean initSequenceBean;
@Test
public void initSequenceBeanTest() {
log.info("Finish: {}", initSequenceBean.toString());
}
}