[英]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.