Spring @Configuration如何缓存对bean的引用 [英] How does Spring @Configuration cache references to beans

查看:191
本文介绍了Spring @Configuration如何缓存对bean的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用基于Java的配置时,Spring如何防止再次调用bar()?

How does Spring prevent a second call to bar() when using Java based configurations?

我想知道编译时注释处理还是通过代理方法?

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);

由于@Configuration,Spring将创建类型为AppConfig的bean并对其进行代理,因为它具有@Bean方法.您应该在ConfigurationClassEnhancer中查看

Because of @Configuration, Spring will create a bean of type AppConfig and proxy it because it has @Bean methods. You should check out ConfigurationClassEnhancer for implementation details.

这些方法不会直接在对象上调用.显然,它们不能,因为在编译时不知道它们.通过在代理上进行反射来调用它们.

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.

因此,当您拥有

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

等效于

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

this所指的是一个代理,该代理缓存方法调用的结果,如果以前调用过它,则立即将其返回.

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.

这篇关于Spring @Configuration如何缓存对bean的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆