问题描述
在 xml 中定义这样的 bean 的编程等价物是什么:
<bean id="foo" class="com.bizz.Foo" />
理想情况下,我希望能够在不使用 XML 和调用 new
的情况下让 spring 创建该 bean,并且这发生在 @Configuration
类型类中。例如:
@Configuration
public ConfigBar {
@Bean
public com.bizz.Foo foo() {
return /* Programmatic equivalent of <bean id="foo" class="com.bizz.Foo" /> here*/;
}
}
我不认为 new Foo()
是等效的:
我知道 spring 正在做一些反思来实现这一目标,但简单地说这不是这个问题的答案。
那么我们如何让 spring 以编程方式创建 Foo
bean,让 spring 注入依赖项、选择构造函数以及 spring 在 XML 中定义时通常会执行的其他任务?
解决方法
等价物是 @Component
或其任何变体,例如 @Controller
或 @Service
。只要您的 bean 位于组件扫描中包含的包中,Spring 就能够在运行时找到您的 bean 并将其注入其他 bean。
举个例子:
@Component
public class Foo {
//...
}
@Service
public class Bar {
// Spring will find and inject Foo bean creating it if necessary when
// creating the Bar "service" bean
@Autowired
private Foo foo;
//...
}
,
我已经解决了:
@Bean
@Autowired
public Foo foo(AutowireCapableBeanFactory autowireCapableBeanFactory) {
return autowireCapableBeanFactory.createBean(Foo.class);
}