我现在是 Spring 的新手。我试图遵循调用PostConstruct和BeanPostProcessor的顺序。
根据我的了解,以下是顺序:-
但是我看到以下顺序:
SpringConfig文件foo.xml
删除了bean标签
上下文:component-scan base-package =“springtest”
@Component
public class MySpring implements ApplicationContextAware,BeanPostProcessor{
public static int temp =0;
public MySpring(){
System.out.println("Initializing MySpring Constructor");
}
@PostConstruct
public void temp(){
System.out.println("PostConsturct" + this.getClass());
temp++;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Before BPP " + bean.getClass());
return this;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("After BPP " + bean.getClass());
return this;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("Initializing ApplicationContext");
}}
回复
MySpring.temp的值为3表示PostContruct被调用了3次。
有人可以在上面帮助我吗...
最佳答案
之所以被调用了三次,是因为您要用MySpring
bean替换每个bean。
你的方法
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Before BPP " + bean.getClass());
return this;
}
返回
this
,实际上表示您当前正在处理的bean对象应替换为MySpring
对象。您可以通过尝试从ApplicationContext
获取任何其他bean来验证这一点。AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigurationBean.class);
ctx.getBean(ConfigurationBean.class);
这将失败,并带有
NoSuchBeanDefinitionException
。您的后处理方法应返回其
bean
参数的值。public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Before BPP " + bean.getClass());
return bean;
}
@PostConstruct
调用是用自己的BeanPostProcessor
CommonAnnotationBeanPostProcessor
实现的。已注册的BeanPostProcessor
实例按顺序使用。当您的
ApplicationContext
初始化您的MySpring
实例时,该CommonAnnotationBeanPostProcessor
已被初始化,因此将处理您的bean。 MySpring
完全初始化之后,Spring会检测到它是BeanPostProcessor
并进行注册。它在CommonAnnotationBeanPostProcessor
之前注册它(BeanPostProcessor
实例有一个优先级设置)。