Search code examples
javaspringjavabeans

Java Spring configuration when to define bean and when new


I have a configuration class and I was wondering should I define bean to each class or create new.

@Configuration
public class BookConfig {

  @Bean
  public Read readBook() {
    return new ReadBook(new Operation(), new Library(new Location()));
  }
}

OR

@Configuration
public class BookConfig {

  @Bean
  public Operation operation() {
    return new Operation();
  }

  @Bean
  public Location location() {
    return new Location();
  }

  @Bean
  public Library library() {
    return new Library(location());
  }

  @Bean
  public Read readBook() {
    return new ReadBook(operation(), library());
  }
}

What is the correct way?


Solution

  • If you do not intend to use Operation and Location bean any time then you can skip creation of that bean and use new as in the first option. But if you think that Operation and Location beans would be used later second approach is better. Though I would suggest a slight modification. You do not have to call the methods instead pass the bean itself as method param.

    @Configuration
    public class BookConfig {
    
      @Bean
      public Operation operation() {
        return new Operation();
      }
    
      @Bean
      public Location location() {
        return new Location();
      }
    
      @Bean
      public Library library(Location location) {
        return new Library(location);
      }
    
      @Bean
      public Read readBook(Location location, Library library) {
        return new ReadBook(location, library);
      }
    }