Spring - Using @Primary annotation

[Last Updated: Aug 31, 2016]

As we saw in Inject Spring Bean By Name example that if there are more than one instances available for an injection point then we have to use @Qualifier annotation to resolve ambiguity. As @Qualifier is used at injection point, there might be two situations where we don't want to or cannot use @Qualifier.

  1. Our autowiring mode is Autowire.BY_TYPE. Then of course we cannot use @Qualifier because we actually don't have user defined injection point specified as @Autowired or @Inject
  2. We want to do bean selection (i.e. resolve the ambiguity) at configuration time rather than during beans development time.

The solution to above problems is to use @Primary annotation.

@Primary indicates that a particular bean should be given preference when multiple beans are candidates to be autowired to a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.


In this example we are going to demonstrate how to use @Primary when autowiring mode is set to Autowire.BY_TYPE

Example Project

Dependencies and Technologies Used:

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

Using Spring Primary Annotation Select All Download
  • spring-primary-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also