[英]How does a Spring Boot Application create beans without @Configuration class
[英]How does Spring @Configuration cache references to beans
在使用基於Java的配置時,Spring如何阻止對bar()的第二次調用?
我想知道編譯時注釋處理或通過代理方法?
@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Foo foo2() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}
假設您創建了一個類似的上下文
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
由於@Configuration
,Spring將創建一個AppConfig
類型的bean並代理它,因為它有@Bean
方法。 您應該查看ConfigurationClassEnhancer
以獲取實現細節。
不直接在對象上調用這些方法。 顯然他們不能,因為他們在編譯時不知道。 它們通過代理上的反射來調用。
所以,當你有
@Bean
public CustomBean foo() {
return new CustomBean(bar());
}
這相當於
@Bean
public CustomBean foo() {
return new CustomBean(this.bar());
}
this
是指一個代理,它緩存方法調用的結果,如果以前調用它,則立即返回它。
Spring不會“阻止”調用bar()
。 相反,在啟動時,spring會生成一個@Bean
標記方法列表,然后調用每個方法一次。 如果你願意,你可以撥打bar()
一百次。 然而春天; 只會叫它一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.