spring - Spring中的构造函数注入(inject)

标签 spring constructor-injection

我正在编写一个代码,其中类 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/

相关文章:

java - 在 spring view : IllegalStateException: Neither BindingResult nor plain target object 中使用 commandName

c# - 具有值类型和对象类型依赖关系的 IoC

java - Junit集成测试

mvvm - 使用 AvalonDock 将实例化的 ViewModel 注入(inject)到 View 中

database - 具有插入或更新机制的Spring批处理自定义itemWriter

mysql - 如何在 Docker 容器中设置 'spring.datasource.url'

unit-testing - 按契约(Contract)设计,编写测试友好的代码,对象构造和依赖注入(inject)将所有最佳实践结合在一起

Spring框架中的Java配置

java - 如何从 Spring MVC 登录

java - 如何以编程方式实例化 Spring Boot 测试?