Issue
If a service bean depends on another: is there any difference between injecting that bean as a method parameter, or fetching from the method reference directly?
@Configuration
public class MyConfig {
@Bean
public SomeService some() {
return new SomeService();
}
@Bean
public AddService add(SomeService some) {
return new AddService(some);
}
//alternative:
//@Bean
//public AddService add() {
// return new AddService(some());
//}
}
Solution
Short answer
There is no difference, but the first method is preferable.
Long answer
You don't work with a MyConfig
instance, you implicitly interact with an in-memory subclass generated by cglib and backed by Spring's package org.springframework.cglib.proxy
(with classes like Enhancer
, MethodProxy
, etc.).
As debugging might reveal, they usually are called ClassName$$EnhancerBySpringCGLIB$$XXXXXXXX
or something.
When BeanFactory
starts initialising beans, it already works with cglib proxies. Proxies' methods are constructed to meet Spring's requirements (e.g. each call of a @Bean
method will return the same instance).@Scope("singleton")
It makes possible to declare inter-bean dependencies. In the second method, we use some()
or this.some()
knowing that it will be referring to a proxy method at runtime.
Why would I recommend the first approach?
You immediately see what dependencies are required for a bean - they all are listed in the signature.
Answered By - Andrew Tobilko