1、init-method方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。init-method需要在applicationContext.xml配置文档中bean的定义里头写明;
springboot如何配置见https://www.jianshu.com/p/b5eb1f6982c5
2、afterPropertiesSet方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。afterPropertiesSet 必须实现 InitializingBean接口。实现 InitializingBean接口必须实现afterPropertiesSet方法。
3、BeanPostProcessor,针对所有Spring上下文中所有的bean,可以在配置文档applicationContext.xml中配置一个BeanPostProcessor,然后对所有的bean进行一个初始化之前和之后的代理。BeanPostProcessor接口中有两个方法: postProcessBeforeInitialization和postProcessAfterInitialization。 postProcessBeforeInitialization方法在bean初始化之前执行, postProcessAfterInitialization方法在bean初始化之后执行。
测试bean:
import javax.annotation.PostConstruct;
public class TestInitialization implements InitializingBean {
private String name ="wangwu";
public TestInitialization(){
System.out.println("===========TestInitialization=========="+name);
}
public void init(){
System.out.println("===========init==========="+name);
}
@PostConstruct
public void postConstruct(){
System.out.println("===========postConstruct===========" +name);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("===========afterPropertiesSet==========="+name);
}
}
自定义BeanPostProcessor
@Component
public class TestBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof TestInitialization){
System.out.println();
System.out.println("BeanPostProcessor:" + "postProcessBeforeInitialization");
Field field = null;
try {
field = bean.getClass().getDeclaredField("name");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
try {
Object o = field.get(bean);
System.out.println( "属性name已注入:" + (o != null));
System.out.println( "属性name已注入:" + o);
System.out.println();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof TestInitialization){
System.out.println();
System.out.println("BeanPostProcessor:" + "postProcessAfterInitialization");
Field field = null;
try {
field = bean.getClass().getDeclaredField("name");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
try {
Object o = field.get(bean);
System.out.println( "属性name已注入:" + (o != null));
System.out.println( "属性name已注入:" + o);
System.out.println();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return bean;
}
}
执行结果如下:

总之,afterPropertiesSet 和init-method之间的执行顺序是afterPropertiesSet 先执行,init-method 后执行。从BeanPostProcessor的作用,可以看出最先执行的是postProcessBeforeInitialization,然后是afterPropertiesSet,然后是init-method,然后是postProcessAfterInitialization。
网友评论