在春季,我可以从自动接线的Bean内部自动接线新的咖啡豆吗? [英] In Spring, can I autowire new beans from inside an autowired bean?

查看:62
本文介绍了在春季,我可以从自动接线的Bean内部自动接线新的咖啡豆吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常只是将事物自动装配到弹簧对象中.但是我遇到一种情况,我需要动态创建一些对象,这些对象需要可以自动装配的值.

I normally just @Autowire things into spring objects. But I've encountered a situation where I need to dynamically create some objects which require values that could be autowired.

我该怎么办?我所能做的就是手动将自动装配的值传递到新对象的构造函数中.我想做的就是在创建新对象时自动为其布线.

What should I do? What I could do is just manually pass the autowired values into the constructor of the new objects. What I would like to do is just autowire each new object as I create it.

@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);
        }
        // ...
    }
}

理想情况下,此bean中没有任何配置信息.它是自动接线的,因此需要通过自动接线将新的bean自动接线所需的所有对象.

Ideally I wouldn't have any configuration information in this bean. It's autowired, so any objects it needs to do the autowiring of the new beans should be available to it by autowiring them in.

推荐答案

您可以使用

You can use AutowireCapableBeanFactory:

@Service 
public class Foo { 
    @Autowired private AutowireCapableBeanFactory factory; 

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

这篇关于在春季,我可以从自动接线的Bean内部自动接线新的咖啡豆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆