我正在编写一个代码,其中类 A 使用类 B 的参数化构造函数构造类 B 的对象。到目前为止,类 B 尚未通过 spring 注入(inject)。要求是我应该始终有一个新的 B 类非单例对象。代码看起来像这样:
class A{
private List<ClassB> classBList = new ArrayList<ClassB>();
void parseInfo(File f, Element e){
ClassB b = new ClassB(this,f,e);
classBList.add(b);
}
}
如果我必须使用 spring 注入(inject) B 类,我的 spring-config 应该是什么样子?
最佳答案
将 bean 定义为原型(prototype)
<!-- A bean definition with singleton scope -->
<bean id="classBBean" class="ClassB" scope="prototype"/>
使用applicationContext getBean每次通过传递参数来创建bean的方法。
class A implements ApplicationContextAware{
private List<ClassB> classBList = new ArrayList<ClassB>();
@Autowired
private ApplicationContext appContext;
void parseInfo(File f, Element e){
ClassB b = (ClassB)appContext.getBean("classBBean",new Object[]{this,f,e});
classBList.add(b);
}
}
关于spring - Spring中的构造函数注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725869/