Spring: Configuration

43 Views Asked by At

In Spring Java configuration, suppose I want to re-use a @Bean in another @Bean definition. I can do this either in one file:

@Bean
public A buildA() {
    return new A();
}

@Bean
public B buildB() {
    return new B(buildA());
}

or I can configure A in one file and autowire it in another file like (field injection for brevity):

@Autowired
private A a;

@Bean
public B buildB() {
    return new B(a);
}

I wonder, if the two possibilities are exactly the same? For me it looks as if, the first version might instatiate A twice, while the second doesn't.

I am asking this, since in my special use case, A is establishing a connection to a messaging broker and I have several Bs that consume the stream (I use .toReactivePublisher() from spring integration in A), and I don't want to connect twice or more to the broker.

1

There are 1 best solutions below

0
Sync On BEST ANSWER

Yes, they're exactly the same. Multiple calls to a @Bean annotated method will not create multiple instances of the same bean.

For an explanation on why it doesn't happen, please see this answer.