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.

Artem Bilan
  • 113,505
  • 11
  • 91
  • 118
PeMa
  • 1,559
  • 18
  • 44
  • 2
    First version does not instantiate A twice, that construction is very common. Spring beans are singleton by default. – Victor May 08 '19 at 13:35
  • Does this still apply, if I have more than one @Bean of type A? – PeMa May 08 '19 at 13:39
  • 2
    Another option is passing `A` as a parameter to `buildB`: `@Bean public B buildB(A a) { return new B(a); }` – Jesper May 08 '19 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? – PeMa May 08 '19 at 14:01
  • Possible duplicate of [Calling a @Bean annotated method in Spring java configuration](https://stackoverflow.com/questions/27990060/calling-a-bean-annotated-method-in-spring-java-configuration) – Nathan Hughes May 08 '19 at 14:06
  • 1
    Yes, you can use `@Qualifier` on a parameter. – Jesper May 08 '19 at 14:08
  • @Jesper Thank you. – PeMa May 08 '19 at 14:45

1 Answers1

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.

Sync
  • 3,571
  • 23
  • 30