In Spring, can I autowire new beans from inside an autowired bean?

自作多情 提交于 2020-01-21 03:24:05

问题


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

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.


回答1:


You can use AutowireCapableBeanFactory:

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

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


来源:https://stackoverflow.com/questions/2383205/in-spring-can-i-autowire-new-beans-from-inside-an-autowired-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!