Close

Spring - Dependency injection in @Bean method parameters

[Updated: Sep 2, 2016, Created: Sep 2, 2016]

In a @Configuration class, the methods annotated with @Bean may depend on other beans to initialize themselves. Other beans, of course, should be annotated with @Bean as well to register with the Spring container.

Spring provides a mechanism where we can pass such bean dependencies with @Bean method parameters. They are injected by the framework just like a constructor dependencies are resolved.

There are following scenarios:



  1. Injecting by type:

    If there's only one bean instance available to be injected to the injection target point then it will be injected successfully by type.


  2. Injecting by name:

    If there are more than one instance of the same type available for a target injection point then there's a conflict (ambiguity). Spring doesn't know which particular instance to be injected in that case. If the name of parameter is same as bean provider method (the factory method) name then the dependency is resolved by name.

    The bean provider method can provide a different name than the method name by using @Bean(name = ...), the injection point method's parameter name should match in that case as well.


  3. Injecting by bean's name with matching @Qualifier:

    If there's an ambiguity then it can also be resolved if the injection point method parameter add a @Qualifier annotation with matching target bean's name.


  4. Injecting by matching @Qualifiers

    Ambiguity can also be resolve by using @Qualifier on the both sides. This is important when a bean provider method has already indented to be exposed as a @Qualifier per business logic sense, so that a particular bean's implementation can be changed without updating all injection points.




Example project

Dependencies and Technologies Used:

  • Spring Context 4.3.2.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Javaconfig Bean Method Dependency Select All Download
  • bean-method-parameters
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also