![](/img/trans.png)
[英]How can I view the Bean Graph for @Autowired beans in Spring STS?
[英]In Spring, can I autowire new beans from inside an autowired bean?
我通常只是@Autowire东西成春天的对象。 但是我遇到了一种情况,我需要动态创建一些需要可以自动装配的值的对象。
我该怎么办? 我能做的只是手动将自动装配的值传递给新对象的构造函数。 我想做的就是在创建它时自动装配每个新对象。
@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进行自动装配的对象。
您可以使用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.