java - 如何使用运行时参数创建原型(prototype)范围的 @Bean?使用 getBean(String name, Object...args)?

标签 java spring dependency-injection inversion-of-control spring-ioc

如何使用运行时参数创建原型(prototype)范围的 @Bean?使用 getBean(String name, Object...args) ? 我的问题是 this question 的结果.

为什么 Spring IoC documentation 中没有使用或提及这种方法?

这是正常方法吗?是否有更正确的方法来创建带有运行时参数的原型(prototype)@Bean?

如果这不是正常方法,那么您能解释一下原因吗? 注意,我需要通过构造函数设置参数,而不是通过 setter 。

@Autowired
private ApplicationContext appCtx;

public void onRequest(Request request) {
    //request is already validated
    String name = request.getParameter("name");
    Thing thing = appCtx.getBean(Thing.class, name);

    //System.out.println(thing.getName()); //prints name
}

-

public class Thing {

    private final String name;

    @Autowired
    private SomeComponent someComponent;

    @Autowired
    private AnotherComponent anotherComponent;

    public Thing(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

最佳答案

就构造函数注入(inject)而言,没有。但是,您可以为 Thing 提供 init 方法并使用 ObjectFactory:

@Autowired
private ObjectFactory<Thing> thingFactory;

public void onRequest(Request request) {
    //request is already validated
    Thing thing = thingFactory.getObject();
    thing.init("name");

    //System.out.println(thing.getName()); //prints name
}

事情是:

@Component
@Scope("prototype")
public class Thing {

    private String name;

    @Autowired
    private SomeComponent someComponent;

    @Autowired
    private AnotherComponent anotherComponent;

    public init(String name) {
        this.name = name;
    }

}

不幸的是,name不能是final,因为它不是通过构造函数实现的。很想看看是否有更好的方法通过构造函数注入(inject)来做到这一点。

关于java - 如何使用运行时参数创建原型(prototype)范围的 @Bean?使用 getBean(String name, Object...args)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50536771/

相关文章:

java - 在现有类上使用派生类 - 继承

java - 在 web 应用上下文中导入时,在 jar 文件中配置的 PersistenceUnit 具有错误的 PersistenceUnitRootLocation URL

java - 了解对 DI 框架的需求

android - 从 Application.Context 获取当前 Activity - MonoAndroid

java - Lambda:使用 Runnable 实例启动的可调用变量

java.lang.IllegalArgumentException : contentIntent required 异常

java - 在德国打发时间 - Android

java - Spring Rest Web 服务返回 415

javascript - 在 AngularJS 中注入(inject)原始类型

java - 策略模式 - 如何注入(inject)策略 - NoUniqueBeanDefinitionException