[英]In Spring, can I autowire new beans from inside an autowired bean?
I normally just @Autowire things into spring objects. 我通常只是@Autowire东西成春天的对象。 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. 理想情况下,我在这个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.
它是自动装配的,因此通过自动装配它们可以使用任何需要对新bean进行自动装配的对象。
You can use AutowireCapableBeanFactory
: 您可以使用
AutowireCapableBeanFactory
:
@Service
public class Foo {
@Autowired private AutowireCapableBeanFactory factory;
private <T> T createAutowiredObject(Class<T> c) {
return factory.createBean(c);
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.