Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling @Bean methods create a new instance of the object or the bean instance?

Tags:

java

spring

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;
    }
}
like image 799
Glide Avatar asked Oct 31 '25 04:10

Glide


1 Answers

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.

like image 111
ekem chitsiga Avatar answered Nov 01 '25 20:11

ekem chitsiga