How to correctly use a @Bean method?

Viewed 391

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 Answers

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

Related