How does Spring @Configuration cache references to beans

前端 未结 2 1058
北荒
北荒 2021-01-19 03:58

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?

2条回答
  •  再見小時候
    2021-01-19 05:06

    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. 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.

    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.

提交回复
热议问题