Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Bean initialization - difference between parameter injection vs. direct method access?

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());
   //}
}
like image 679
membersound Avatar asked Jul 29 '26 00:07

membersound


1 Answers

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@Scope("singleton") method will return the same instance).

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.

like image 121
Andrew Tobilko Avatar answered Jul 31 '26 13:07

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!