Ashish :
I have to work with existing library of my company which has bunch of @Bean packaged in @Configuration in Spring project but would be added as dependency for my project. The situation would be similar to
@Configuration
Class A{
@Bean
B b(){
return new B()
}
}
@Configuration
Class C{
@Bean
D d(){
D d = new D();
//TODO: How do I use instance of B here
d.someConfiguration(B b);
return d;
}
}
Should I initialized A using new operator in C and call method b or should I @Autowire B
in C directly.
Deadpool :
There are multiple ways you can do this
By field Autowiring
@Configuration
Class C{
@Autowire
private B b;
@Bean
D d(){
D d = new D();
//TODO: How do I use instance of B here
d.someConfiguration(B b);
return d;
}
}
By constructor Autowiring (Personally i prefer using constructor Autowiring which will be help during test cases)
@Configuration
Class C{
private B b;
@Autowire
public C(B b){
this.b=b;
}
@Bean
D d(){
D d = new D();
//TODO: How do I use instance of B here
d.someConfiguration(B b);
return d;
}
}
Or you can just add it as method arguments spring will resolve it
@Configuration
Class C{
@Bean
D d(B b){
D d = new D();
//TODO: How do I use instance of B here
d.someConfiguration(B b);
return d;
}
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=307162&siteId=1