如何使用运行时参数创建原型(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/