在 Spring 中,我可以从自动装配的 bean 内部自动装配新的 bean 吗?
我通常只是将 @Autowire 的东西放入 spring 对象中。但我遇到了一种情况,我需要动态创建一些需要可以自动装配的值的对象。
我应该怎么办?我能做的就是手动将自动装配的值传递到新对象的构造函数中。我想做的只是在创建每个新对象时自动装配它。
@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 的任何对象都应该可以通过自动装配来使用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
AutowireCapableBeanFactory
:You can use
AutowireCapableBeanFactory
: