1. 简介
很多时间当一个Bean被创建出来后,我们希望做一些初始化操作,如初始化数据、缓存预热等。有以下三种方法:
- 初始化方法
initMethod - 注解
@PostConstruct InitializingBean的afterPropertiesSet方法
2. 三种方法实现
先准备一个类用于测试,代码如下:
public class BeanLifeCheck implements InitializingBean {private static final Logger logger = LoggerFactory.getLogger(BeanLifeCheck.class);@Value("${spring.application.name}")private String applicationName;public BeanLifeCheck() {logger.info("BeanLifeCheck: Construct " + applicationName);}public void initMethod() {logger.info("BeanLifeCheck: initMethod " + applicationName);}@PostConstructpublic void postConstruct() {logger.info("BeanLifeCheck: postConstruct " + applicationName);}@Overridepublic void afterPropertiesSet() throws Exception {logger.info("BeanLifeCheck: afterPropertiesSet " + applicationName);}}
2.1 初始化方法initMethod
这个以前是通过xml配置文件来定义的,现在可以直接定义在@Bean注解上,如下:
@Bean(initMethod = "initMethod")public BeanLifeCheck beanLifeCheck() {return new BeanLifeCheck();}
2.2 注解@PostConstruct
直接在方法上加注解即可:
@PostConstructpublic void postConstruct() {logger.info("BeanLifeCheck: postConstruct " + applicationName);}
2.3 InitializingBean的afterPropertiesSet方法
需要类实现接口InitializingBean,如下:
@Overridepublic void afterPropertiesSet() throws Exception {logger.info("BeanLifeCheck: afterPropertiesSet " + applicationName);}
3. 总结
运行后的执行日志及顺序如下:
c.r.springweb.day210911.BeanLifeCheck : BeanLifeCheck: 构造方法 nullc.r.springweb.day210911.BeanLifeCheck : BeanLifeCheck: @postConstruct注解 testBeanInitc.r.springweb.day210911.BeanLifeCheck : BeanLifeCheck: 实现InitializingBean接口afterPropertiesSet testBeanInitc.r.springweb.day210911.BeanLifeCheck : BeanLifeCheck: initMethod testBeanInit
