Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在春天,我可以从自动连线的bean中自动连线新的bean吗?_Java_Spring_Autowired - Fatal编程技术网

Java 在春天,我可以从自动连线的bean中自动连线新的bean吗?

Java 在春天,我可以从自动连线的bean中自动连线新的bean吗?,java,spring,autowired,Java,Spring,Autowired,我通常只是把东西@Autowire到spring对象中。但我遇到了一种情况,我需要动态创建一些需要可以自动连接的值的对象 我该怎么办?我所能做的就是手动将自动连接的值传递到新对象的构造函数中。我想做的只是在创建每个新对象时自动关联它 @Service public class Foo { @Autowired private Bar bar; /** This creates Blah objects and passes in the autowired value. */

我通常只是把东西@Autowire到spring对象中。但我遇到了一种情况,我需要动态创建一些需要可以自动连接的值的对象

我该怎么办?我所能做的就是手动将自动连接的值传递到新对象的构造函数中。我想做的只是在创建每个新对象时自动关联它

@Service
public class Foo {
    @Autowired private Bar bar;

    /** This creates Blah objects and passes in the autowired value. */
    public void manuallyPassValues() {
        List<Blah> blahs = new LinkedList<Blah>();
        for(int i=0; i<5; ++i) {
            Blah blah = new Blah(bar);
            blahs.add(blah);
        }
        // ...
    }

    /** This creates Blah objects and autowires them. */
    public void useAutowire() {
        List<Blah> blahs = new LinkedList<Blah>();
        for(int i=0; i<5; ++i) {
            // How do I implement the createAutowiredObject method?
            Blah blah = createAutowiredObject(Blah.class);
            blahs.add(blah);
        }
        // ...
    }
}
@服务
公开课Foo{
@自动连线私人酒吧;
/**这将创建Blah对象并传入自动关联值*/
public void manuallyPassValues(){
List blahs=newlinkedlist();
对于(int i=0;i您可以使用:

@服务
公共类Foo{
@自动接线私人自动接线工厂;
私有T createAutowiredObject(c类){
返回factory.createBean(c);
}
...
}
@Service 
public class Foo { 
    @Autowired private AutowireCapableBeanFactory factory; 

    private <T> T createAutowiredObject(Class<T> c) {
        return factory.createBean(c);
    }
    ...
}