3

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());
   //}
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 3
    When you use `@Configuration` there is no difference. Read this please: https://docs.spring.io/spring/docs/5.0.7.RELEASE/spring-framework-reference/core.html#beans-java – Alexander Polozov Jul 25 '18 at 15:15

1 Answers1

6

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142