我目前是 Spring 的新手。我试图遵循调用 PostConstruct 和 BeanPostProcessor 的顺序。
根据我的了解,以下是顺序:-
- BPP -> postProcessBeforeInitialization
- 后构造
- BPP -> postProcessAfterInitialization
但是我看到遵循以下顺序:-
- 施工后
- BPP -> postProcessBeforeInitialization
- 后构造
- BPP -> postProcessAfterInitialization
SpringConfig文件foo.xml 删除了 beans 标签 上下文:组件扫描基础包=“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 构造器
- 初始化ApplicationContext
- PostConsturctclass springtest.MySpring
- 在属性设置类 springtest.MySpring 之后
- 在 BPP 类 org.springframework.context.event.EventListenerMethodProcessor 之前
- PostConsturctclass springtest.MySpring
- 在属性设置类 springtest.MySpring 之后
- 在 BPP 类 springtest.MySpring 之后
- 在 BPP 类 org.springframework.context.event.DefaultEventListenerFactory 之前
- PostConsturctclass springtest.MySpring
- 在属性设置类 springtest.MySpring 之后
- 在 BPP 类 springtest.MySpring 之后
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
实例有一个优先级设置)。
关于java - PostConstruct 在 BeanPostProcessor 之前被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556854/