Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Spring, can I autowire new beans from inside an autowired 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);
        }
        // ...
    }
}

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.

like image 640
HappyEngineer Avatar asked Mar 04 '10 22:03

HappyEngineer


1 Answers

You can use AutowireCapableBeanFactory:

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

    private <T> T createAutowiredObject(Class<T> c) {
        return factory.createBean(c);
    }
    ...
}
like image 71
axtavt Avatar answered Nov 14 '22 22:11

axtavt