简体   繁体   English

Spring @Configuration如何缓存对bean的引用

[英]How does Spring @Configuration cache references to beans

How does Spring prevent a second call to bar() when using Java based configurations? 在使用基于Java的配置时,Spring如何阻止对bar()的第二次调用?

I'm wondering compile time annotation processing or by proxying the method? 我想知道编译时注释处理或通过代理方法?

@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();
  }
}  

Assuming you created your context a little something like 假设您创建了一个类似的上下文

AnnotationConfigApplicationContext context =
    new AnnotationConfigApplicationContext(AppConfig.class);

Because of @Configuration , Spring will create a bean of type AppConfig and proxy it because it has @Bean methods. 由于@Configuration ,Spring将创建一个AppConfig类型的bean并代理它,因为它有@Bean方法。 You should check out ConfigurationClassEnhancer for implementation details. 您应该查看ConfigurationClassEnhancer以获取实现细节。

These methods aren't called on the object directly. 不直接在对象上调用这些方法。 Obviously they can't since they aren't known at compile time. 显然他们不能,因为他们在编译时不知道。 They are called through reflection on the proxy. 它们通过代理上的反射来调用。

So when you have 所以,当你有

@Bean
public CustomBean foo() {
    return new CustomBean(bar());
}

which is equivalent to 这相当于

@Bean
public CustomBean foo() {
    return new CustomBean(this.bar());
}

the this is referring to a proxy which caches the result of the method invocation and returns it immediately if it's called it before. this是指一个代理,它缓存方法调用的结果,如果以前调用它,则立即返回它。

Spring does not "prevent" a call to bar() . Spring不会“阻止”调用bar() Instead, at startup, spring generates a list of @Bean marked methods then calls each method one time. 相反,在启动时,spring会生成一个@Bean标记方法列表,然后调用每个方法一次。 If you want, you can call bar() a hundred times. 如果你愿意,你可以拨打bar()一百次。 Spring, however; 然而春天; will only call it one time. 只会叫它一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM