![](/img/trans.png)
[英]What is the xml equivalent of this bean configuration where an object is being passed for which there is no bean configuration defined?
[英]What is the programatic equivalent of a XML defined spring bean
在 xml 中定義這樣的 bean 的程序等效項是什么:
<bean id="foo" class="com.bizz.Foo" />
理想情況下,我希望能夠讓 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*/;
}
}
我不認為new Foo()
是等價的:
我知道 spring 正在做一些反思來實現這一點,但簡單地說這不是這個問題的答案。
那么我們如何讓 spring 以編程方式創建Foo
bean,讓 spring 注入依賴項、選擇構造函數以及 spring 在 XML 中定義時通常會執行的其他任務?
等效項是@Component
或其任何變體,例如@Controller
或@Service
。 只要你的bean在package包含在組件掃描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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.