[英]What is the programatic equivalent of a XML defined spring bean
What is the programatic equivalane to defining a bean like this in xml:在 xml 中定义这样的 bean 的程序等效项是什么:
<bean id="foo" class="com.bizz.Foo" />
Ideally I would like to be able to have spring create that bean, without using XML and without calling new
and for this to happen within a @Configuration
type class. For example:理想情况下,我希望能够让 spring 创建那个 bean,而不使用 XML 并且不调用
new
并且为了在@Configuration
类型 class 中发生这种情况。例如:
@Configuration
public ConfigBar {
@Bean
public com.bizz.Foo foo() {
return /* Programmatic equivalent of <bean id="foo" class="com.bizz.Foo" /> here*/;
}
}
I don't think new Foo()
is equivalent:我不认为
new Foo()
是等价的:
I know that spring is doing some reflection to achieve this, however simply stating that is not the answer to this question.我知道 spring 正在做一些反思来实现这一点,但简单地说这不是这个问题的答案。
so how can we let spring create the Foo
bean programmatically letting spring inject dependencies, pick the constructor and perhaps other tasks that spring would normally do when defined in XML?那么我们如何让 spring 以编程方式创建
Foo
bean,让 spring 注入依赖项、选择构造函数以及 spring 在 XML 中定义时通常会执行的其他任务?
The equivalent is @Component
or any variant thereof such as @Controller
or @Service
.等效项是
@Component
或其任何变体,例如@Controller
或@Service
。 So long as your bean is in a package included in the component scan Spring will be able to find your bean at runtime and inject it into other beans.只要你的bean在package包含在组件扫描Spring中,就能在运行时找到你的bean并将它注入到其他bean中。
As an example:举个例子:
@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;
//...
}
I have worked it out:我已经解决了:
@Bean
@Autowired
public Foo foo(AutowireCapableBeanFactory autowireCapableBeanFactory) {
return autowireCapableBeanFactory.createBean(Foo.class);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.