3

In the code below, is calling bar() inside foo.setBar(bar()) and blah.setBar(bar()) using two difference instances of Bar? Or is it using a bean instance of Bar instead? If it's a bean instance, how does Spring do it automagically? Is it achieved by proxy?

@Configuration
public class AppConfig {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setBar(bar());
        return foo;
    }

    @Bean
    public Bar bar() {
        return new Bar();
    }

    @Bean
    public Blah blah() {
        Blah blah = new Blah();
        blah.setBar(bar());
        return blah;
    }
}
Glide
  • 20,235
  • 26
  • 86
  • 135

3 Answers3

7

Spring creates a proxy of your @Configuration annotated classes. This proxy intercepts @Bean method calls and caches the bean instances so that further calls to the same @Bean method refers to the same bean instance.

Hence in your case both calls to bar() method refers to the same Bar instance.The Bar instance is actually a singleton per application context.This is why the @Bean methods visibility is restricted to either protected , package or public because Spring needs to override your @Bean methods in the proxy.

ekem chitsiga
  • 5,523
  • 2
  • 17
  • 18
1

Single bean instance will be used and it is achieved using proxies. Spring uses the concept of Inheritance based proxies to achieve this. Please take a look at - How to exactly work the Spring Inheritance-based Proxies configuration?

Community
  • 1
  • 1
asg
  • 2,248
  • 3
  • 18
  • 26
0

the same bean instance will be used in your case because a singleton scope is used by default for '@Bean' annotation.

yes, it's achived by spring proxying internals.

ivanenok
  • 594
  • 5
  • 9