作用
由Spring提供,在设置完Bean的所有属性后被调用,主要用于执行一些初始化操作和检查属性是否合规。使用JDK提供的注解@PostConstruct同样可以实现这些功能,详见:@PostConstruct注解的使用
执行顺序
构造方法 -> 依赖注入 -> @PostConstruct -> afterPropertiesSet -> @PreDestroy
代码验证
@Slf4j
@Component
public class MyComponentA implements InitializingBean {
private static MyComponentB myComponentB;
public MyComponentA() {
log.info("执行-> 构造方法");
}
// 这里顺便验证了下自动注入static属性
@Autowired
public void setMyComponentA(MyComponentB myComponentB) {
MyComponentA.myComponentB = myComponentB;
log.info("执行-> 依赖注入 MyComponentB");
}
public void init() {
log.info("执行-> init 方法");
}
@PostConstruct
public void postConstruct() {
log.info("执行-> PostConstruct 方法");
}
@PreDestroy
public void preDestroy() {
log.info("执行-> PreDestroy 方法");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("执行-> afterPropertiesSet 方法");
}
}
@Component
public class MyComponentB {
}
结果:
执行-> 构造方法
执行-> 依赖注入 MyComponentB
执行-> PostConstruct 方法
执行-> afterPropertiesSet 方法
执行-> PreDestroy 方法