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;
    }
}
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With