laahaa
laahaa

Reputation: 347

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:

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

Upvotes: 0

Views: 55

Answers (2)

rdas
rdas

Reputation: 21295

You can use an argument injection to let spring know that the DogHouse bean requires the Dog bean.

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

Spring will inject the Dog bean into the method while constructing the DogHouse bean.

Upvotes: 1

Nishant Middha
Nishant Middha

Reputation: 302

@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.

Upvotes: 1

Related Questions