2

I'm new to Spring. What’s the difference between these two ways of injecting beans in @Bean methods? Which one should I use, and why?

@Configuration
public class AppConfig {

 @Bean
 public Foo foo(Bar bar) {
  return new Foo(bar);
 }

 @Bean
 public Bar bar() {
  return new Bar("bar1");
 }

}

And

@Configuration
public class AppConfig {

 @Bean
 public Foo foo() {
  return new Foo(bar());
 }

 @Bean
 public Bar bar() {
  return new Bar("bar1");
 }

}

1 Answers1

-1

2nd Approach is not correct, because bar() method is already called by Spring to create the Bar Object, and if we call the bar() method manually again in foo() method, we are creating one more object which is not necessary

In other words: In first approach only one object of Bar will be create while in 2nd approach 2 objects of Bar will be created (one by Spring, and one by us) which is unnecessary

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
  • 3
    This is wrong, in both cases Spring will use the same object, because with configuration classes (i.e. classes with the annotation `@Configuration`), Spring will use proxies and intercept the method calls (check the documentation: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-java-configuration-annotation) – dunni Mar 29 '22 at 14:40
  • 1
    thanks @dunni for correcting, documentation says there will be only one instance created, that means both the approaches mentioned in the questions are same!! – Shridutt Kothari Mar 29 '22 at 14:47