在bean被放进去容器之前,执行操作,有很多种方法,这里做一个总结
spring的bean有两种,一种beanFactory创建出来的bean,叫工厂bean(最原始的bean),还有一种是普通bean
1.通过覆写无参构造方法(构造块)
spring反射创建bean是通过无参构造方法+set方法注入
2.通过postConstruct注解
3.通过afterPropertiesSet指定方法
4.通过Spring指定init方法
其他配置执行前后的方法
1、init-method方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。init-method需要在applicationContext.xml配置文档中bean的定义里头写明。例如:<bean id="TestBean" class="nju.software.xkxt.util.TestBean" init-method="init"></bean>
这样,当TestBean在初始化的时候会执行TestBean中定义的init方法。
2、afterPropertiesSet方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。afterPropertiesSet 必须实现 InitializingBean接口。实现 InitializingBean接口必须实现afterPropertiesSet方法。
3、BeanPostProcessor,针对所有Spring上下文中所有的bean,可以在配置文档applicationContext.xml中配置一个BeanPostProcessor,然后对所有的bean进行一个初始化之前和之后的代理。BeanPostProcessor接口中有两个方法: postProcessBeforeInitialization和postProcessAfterInitialization。 postProcessBeforeInitialization方法在bean初始化之前执行, postProcessAfterInitialization方法在bean初始化之后执行。
总之,afterPropertiesSet 和init-method之间的执行顺序是afterPropertiesSet 先执行,init-method 后执行。从BeanPostProcessor的作用,可以看出最先执行的是postProcessBeforeInitialization,然后是afterPropertiesSet,然后是init-method,然后是postProcessAfterInitialization。
@Component
public class TestDao implements InitializingBean, DisposableBean {
public TestDao() {
System.out.println("constructor");
}
@Async
public void query(){
System.out.println("Hello Spring!");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");
}
@PostConstruct
public void PostConstruct(){
System.out.println("PostConstruct");
}
public void InitMethod(){
System.out.println("InitMethod");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy");
}
@PreDestroy
public void PreDestroy(){
System.out.println("PreDestroy");
}
public void destroyMethod(){
System.out.println("destroyMethod");
}
}
执行之后打印的结果
总的来说就是打印的结果是构造方法->注解@PostConstruct方法->InitializingBean接口的afterPropertiesSet方法->xml中配置的init-method方法 同理销毁也是一样注解@PreDestroy方法->DisposableBean接口的destroy方法->xml中配置的destroy-method方法