如果我有这样的类(class):
@Service
@Scope("prototype")
public class TraderStarter {
private String address;
}
并且 TraderStarter 应创建 X 次,X 由数据库动态确定。我该如何获得这些 bean ? 就这样?
@Component("SpringContextUtil")
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
}
使用 SpringContextUtil .getBean() 并为每个 TraderStarter 原型(prototype)设置参数? 非常感谢。
最佳答案
简而言之,原型(prototype)意味着新 bean 是在每次请求该 bean 时创建的(注入(inject)不同的类/getBean 调用)。
因此,如果您想创建这些原型(prototype) bean,就会有人触发此过程。
当然,一种方法是使用 ApplicationContext
但在我看来,这是一种不好的方法,因为你的代码会与 spring 耦合。
你不能将原型(prototype)注入(inject)到单例中,这是行不通的。
但是,您可以使用与 Spring 集成的 javax.inject.Provider
接口(interface):
这是一个例子:
// from your example
// you can use injection here and everything, its a regular spring bean
@Service
@Scope("prototype")
public class TraderStarter {
private String address;
public void setAddress(String address) {
this.address = address;
}
}
///////////////////////
@Component
public class MyDbManager {
private Provider<TraderStarter> traderStarterProvider;
public List<TraderStarter> dynamicallyCreateBeans() {
List<String> addresses = dbManager.findAllAddresses();// to to the db, get the data
return
addresses.stream()
.map(this::createTraderStarter) // <-- creates different beans!
.collect(Collectors.toList());
}
private TraderStarter createTraderStarter(String address) {
TraderStarter ts = provider.get();
ts.setAddress(address);
return ts;
}
}
还有其他方法以及工厂(请参阅 ObjectFactory)和创建代理(查找方法和作用域代理),但在我看来,这是最干净的方法。
无论如何,如果您选择其他解决方案,请阅读 this tutorial
关于java - 如何在动态时期使用不同参数创建 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56985806/