Documentation / @Primary
@Primary @Secondary are equivalent to Spring DI @Primary @Secondary and Micronaut @Primary @Secondary.
Note that JSR 330 does not have any equivalent functionality. CDI has a different approach and instead has @Priority, @Default and @Alternative annotations to achieve similar goals.
@Secondary are used when there are
multiple candidates to inject. They provide a "priority" to determine which dependency to
inject and use when injecting a single implementation and multiple candidates are available
We typically use @Primary and @Secondary when we are building multi-module applications. We have multiple modules (jars) that provide implementations. We use @Secondary to indicate a "default" or "fallback" implementation to use and we use @Primary to indicate the best implementation to use when it is available. DInject DI will then wire depending on which modules (jars) are included in the classpath.
A bean with
@Primary is deemed to be highest priority and will be injected and used
when it is available.
There should only ever be one bean implementation marked as @Primary for a given dependency.
This is functionally the same as Spring and Micronaut @Primary.
A bean with
@Secondary is deemed to be lowest priority and will only be injected
if there are no other candidates to inject. We use
@Secondary to indicate a
"default" or "fallback" implementation that will be superseded by any other available implementation.
This is functionally the same as Spring and Micronaut @Secondary.