java – Spring – 动态原型豆

我想动态创建
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");
        }
    }
}

如果我创建一个Configuration类,它似乎仍然是一个Singleton

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");
        }
    }
}

我在这里错过了什么吗?

UPDATE

我最终混合了所提到的一切.

我用@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);
    }
}   

最佳答案 我会使用’工厂’来创建MyObject的实例.

@Named
public class MyObjectFactory {
    public MyObject newInstance() {
        return new MyObject();
    }
}

然后,我会把这个工厂@Inject’加入我的Foo对象.在那里,每当我需要一个,我可以要求一个新的实例.

如果您希望通过Spring中的bean配置新实例,则可能必须将它们注入Factory,并在返回之前设置对象.像这样的东西:

@Named
public class MyObjectFactory {
    @Inject
    private MyOtherObject otherObject;

    public MyObject newInstance() {
        return new MyObject(otherObject);
    }
}
点赞