Reputation: 347
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:
dog()
in dogHouse()
dog()
and dogHouse()
in the same java classIs this possible? If it is, how should I inject the dog Bean in Test class? Thanks.
Upvotes: 0
Views: 55
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
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