[英]Use Spring XML configured bean inside @Configuration Class and Use the bean as factory-bean for another bean
[英]@Bean inside class with @Configuration and without it
Spring 3.0中有一個@Bean
注釋。 它允許直接在Java代碼中定義Spring bean。 在瀏覽Spring引用時,我發現了兩種使用此注釋的不同方法 - 使用@Configuration
注釋的內部類和沒有此注釋的內部類。
本節包含以下代碼:
@Component
public class FactoryMethodComponent {
@Bean @Qualifier("public")
public TestBean publicInstance() {
return new TestBean("publicInstance");
}
// omitted irrelevant method
}
在這里我們可以看到一段非常相似的代碼,但現在@Configuration
就在這里:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
以前的參考部分包含以下解釋:
Spring組件中的@Bean方法的處理方式與Spring @Configuration類中的對應方式不同。 不同之處在於,使用CGLIB不會增強@Component類來攔截方法和字段的調用。 CGLIB代理是調用@Configuration類@Bean方法中的方法或字段創建對協作對象的bean元數據引用的方法。 使用普通的Java語義不會調用方法。 相反,在@Component類@Bean方法中調用方法或字段具有標准Java語義。
但CGLIB是應用程序開發人員不應該意識到的一種內部東西(當然,在理想的世界中)。 據我所知,在兩種情況下,Spring都會調用使用@Bean
注釋的方法來創建Spring bean,在這兩種情況下,這些實例都會注入協作者。
所以我的問題是,作為兩個案例之間的應用程序開發人員,我有什么不同 ?
不同之處在於,使用@Configuration
您可以從另一個方法調用一個@Bean
方法,並獲得一個完全初始化的實例,如下所示:
public class Foo {
@Value("Hello, world!")
public String value;
}
@Configuration
public class Config {
@Bean
public Foo createFoo() {
Foo foo = new Foo();
System.out.println(foo.value); // Prints null - foo not initialized yet
return foo;
}
@Bean
public Bar createBar() {
Foo foo = createFoo();
System.out.println(foo.value); // Prints Hello, world! - foo have been initialized by the interceptor
return new Bar(foo);
}
}
@Bean [實例方法]里面@Component - 一個方法用@Bean實例調用其他方法@Bean實例,那么它將是簡單的java語義調用,即對象不會被Spring容器返回,這將是從java實例工廠正常返回方法,因為Component類不擴展CGLIB。
@Configuration中的@Bean [實例方法] - 在這種情況下,spring容器將返回對exisiting對象的引用。 它不會是正常的java sematic調用。
@Bean on配置和組件類中的靜態方法 - 在這種情況下,@ Bund方法永遠不會被Configuration類和Component Sterotype類中的容器截獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.