1

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.

7
  • 2
    First version does not instantiate A twice, that construction is very common. Spring beans are singleton by default. Commented May 8, 2019 at 13:35
  • Does this still apply, if I have more than one @Bean of type A? Commented May 8, 2019 at 13:39
  • 2
    Another option is passing A as a parameter to buildB: @Bean public B buildB(A a) { return new B(a); } Commented May 8, 2019 at 13:54
  • @Jesper Ok I didn't know that. So I suppose I can use @Qualifier() for the variable and thus specifiy the bean explicitely? Commented May 8, 2019 at 14:01
  • 1
    Yes, you can use @Qualifier on a parameter. Commented May 8, 2019 at 14:08

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.