我想即时创建 Spring Prototype bean(其中包含 @Injects),但没有看到如何执行此操作。一个简单的例子:
@Named
public class Foo{
public void someMethod(){
for(int x=0; x < 10; x++){
MyObject obj = new MyObject(); // How would this work with Prototype
obj.setSomeField("Hello");
}
}
}
@Named
@Scope("prototype")
public class MyObject{
@Inject
SomeDependency blah;
public void setSomeField(String word){}
}
如果我将类 Foo 修改为如下所示,我将无法保证获得一个新实例:
@Named
public class Foo{
@Inject MyObject obj;
public void someMethod(){
for(int x=0; x < 10; x++){
obj.setSomeField("Hello");
}
}
}
如果我创建一个配置类,它似乎也保持为单例
public class Configuration {
@Bean
public MyObject getMyObject(){
return new MyObject();
}
}
@Named
public class Foo{
@Inject Configuration config;
public void someMethod(){
for(int x=0; x < 10; x++){
MyObject obj = config.getMyObject();
obj.setSomeField("Hello");
}
}
}
我在这里错过了什么吗?
更新
我最终混合了所有提到的东西。
我用@Named 和@Scope("prototype") 标记了非单例,并使用通用方法调用它们:
@Named
public MyFileFactory implements ApplicationContextAware{
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
context = ac;
}
public <T> T getNewInstance(final Class<T> type) {
return context.getBean(type);
}
}
前任:
@Named
public class SomeClass{
@Inject
private MyFileFactory myFileFactory;
public void foo(){
final MyObject myObject = myFileFactory.getNewInstance(MyObject.class);
}
}