我有一个Bean,它实现
BeanPostProcessor
public class ScopeTest implements BeanPostProcessor {
public ScopeTest() {
System.out.println("ScopeTest()");
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessBeforeInitialization()");
return null;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInitialization()");
return null;
}
}
我已经在 Spring bean 配置文件中将其配置为 scope
作为 prototype
。
<bean id="st" class="com.test.ScopeTest" scope="prototype" />
我使用 ApplicationContext
运行代码
public class App {
public static void main(String[] args) {
ApplicationContext container = new ClassPathXmlApplicationContext("spring.xml");
}
}
我观察到的输出是
ScopeTest()
这里是什么让容器为没有 getBean()
标记为 prototype
的 bean 创建对象?
最佳答案
原型(prototype)范围在这里不起作用,因为 BeanPostProcessor 实现仅在 Spring 应用程序上下文启动时发现、实例化和注册。这些 bean 按类型(实例化之前/之后等)排序并存储在列表中。从那里,后处理器 bean 被应用于进一步的 bean 创建。与“普通”bean(如服务 bean)相比,它们在启动后不会再次从上下文中检索。因此不考虑它们适用的范围。
关于java - 为什么范围原型(prototype)不适用于实现 BeanPostProcessor 的 spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30069656/