spring中bean初始化的方法以及生命周期

bean初始化有三种方法:

  1. 使用方法上加@PostConstruct
  2. 类实现InitializingBean接口,重写AfterPropertiesSet方法
  3. 通过 元素的 init-method属性配置

且顺序依次是1->2->3

示例:
public class InitSequenceDemoBean implements InitializingBean {

public InitSequenceDemoBean() {  
   System.out.println("InitSequenceBean: constructor");  
}  
 
@PostConstruct  
public void postConstruct() {  
   System.out.println("InitSequenceBean: postConstruct");  
}  
 
public void initMethod() {  
   System.out.println("InitSequenceBean: init-method");  
}  
 
@Override  
public void afterPropertiesSet() throws Exception {  
   System.out.println("InitSequenceBean: afterPropertiesSet");  
}  

}
配置文件中添加如下Bean定义:


输出结果:
InitSequenceBean: constructor
InitSequenceBean: postConstruct
InitSequenceBean: afterPropertiesSet
InitSequenceBean: init-method

通过上述输出结果,说明三种初始化的顺序是:
Constructor > @PostConstruct > InitializingBean > init-method
ps:@Autowired标注的方法在构造器之后,且在初始化方法之前执行,即Constructor >@Autowired标注的方法> @PostConstruct > InitializingBean > init-method
此处,给你留一个问题,详见注释1

bean的生命周期如下:
1)设置属性值;
2)如果该Bean实现了BeanNameAware接口,调用Bean中的BeanNameAware.setBeanName()方法
3)如果该Bean实现了BeanFactoryAware接口,调用Bean中的BeanFactoryAware.setBeanFactory()方法
4)如果该Bean实现了ApplicationContextAware接口,
调用bean中setApplicationContext()方法
5)如果该Bean实现了BeanPostProcessor接口,调用BeanPostProcessors.postProcessBeforeInitialization()方法;@PostConstruct注解后的方法就是在这里被执行的
6)如果该Bean实现了InitializingBean接口,调用Bean中的afterPropertiesSet方法
7)如果在配置bean的时候指定了init-method,例如: 调用Bean中的init-method
8)如果该Bean实现了BeanPostProcessor接口,调用BeanPostProcessors.postProcessAfterInitialization()方法;
9)如果该Bean是单例的,则当容器销毁并且该Bean实现了DisposableBean接口的时候,调用destory方法;如果该Bean是prototype,则将准备好的Bean提交给调用者,后续不再管理该Bean的生命周期。

注释

  1. 下面这段代码会有问题吗?如果有问题如何修正
 @Component
public class LightMgrService {
  @Autowired
  private LightService lightService;
  public LightMgrService() {
    lightService.check();
  }
}
我们在 LightMgrService 的默认构造器中调用了通过 @Autoware 注入的成员变量 LightService 的 check 方法:
@Service
public class LightService {
    public void start() {
        System.out.println("turn on all lights");
    }
    public void shutdown() {
        System.out.println("turn off all lights");
    }
    public void check() {
        System.out.println("check all lights");
    }
}

你可能感兴趣的:(工程设计,java)