1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()); } @Bean public Bar bar() { return new Bar( "bar1" ); } } |
However, there is one alternate way to inject dependency that is not documented well, it is to just take the dependency as a `@Bean` method parameter this way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Configuration public class AppConfig { @Bean public Foo foo(Bar bar) { return new Foo(bar); } @Bean public Bar bar() { return new Bar( "bar1" ); } } |
There is a catch here though, the injection is now by type, the `bar` dependency would be resolved by type first and if duplicates are found, then by name:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Configuration public static class AppConfig { @Bean public Foo foo(Bar bar1) { return new Foo(bar1); } @Bean public Bar bar1() { return new Bar( "bar1" ); } @Bean public Bar bar2() { return new Bar( "bar2" ); } } |
In the above sample dependency `bar1` will be correctly injected. If you want to be more explicit about it, an @Qualifer annotation can be added in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Configuration public class AppConfig { @Bean public Foo foo( @Qualifier ( "bar1" ) Bar bar1) { return new Foo(bar1); } @Bean public Bar bar1() { return new Bar( "bar1" ); } @Bean public Bar bar2() { return new Bar( "bar2" ); } } |
So now the question of whether this is recommended at all, I would say yes for certain cases. For eg, had the bar bean been defined in a different @Configuration class , the way to inject the dependency then is along these lines:
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Configuration public class AppConfig { @Autowired @Qualifier ( "bar1" ) private Bar bar1; @Bean public Foo foo() { return new Foo(bar1); } } |
I find the method parameter approach simpler here:
1 2 3 4 5 6 7 8 9 | @Configuration public class AppConfig { @Bean public Foo foo( @Qualifier ( "bar1" ) Bar bar1) { return new Foo(bar1); } } |
Thoughts?
thanks very much.
ReplyDeleteThis helped a lot!
ReplyDeleteJust what I was looking for! Clearly explained. Much thanks!
ReplyDeletePlease let me know how to call outside the Configuration class beans defined with parameters?
ReplyDeleteThanks
ReplyDelete