Search code examples
javaspringdependency-injectionjavabeans

Is it possible to use a bean generated from the same class


I'm trying to use a bean generated from the same class. E.g:

public class Test {
  ...


  @Bean
  public Dog dog() {
    ...
    return dog;
  }

  @Bean
  public DogHouse dogHouse() {
    Dog d = dog(); // Is this right? Can I inject dog bean here?
    ...
    return dogHouse;
  }
}

Two requirements I got to obey:

  • Use the result of dog() in dogHouse()
  • Keep dog() and dogHouse() in the same java class

Is this possible? If it is, how should I inject the dog Bean in Test class? Thanks.


Solution

  • @Bean
      public DogHouse dogHouse() {
        Dog d = dog();
        ...
        return dogHouse;
      }
    

    When @Bean have dependencies on one another, then to resolve this dependency one bean method can call the other one. In your case calling dog() inside dogHouse() is perfectly fine.