Primaryโ
Indicates that a specific bean is a primary candidate for injection.
Why @Primary is needed?โ
There are situations when it's necessary to register more than one bean of the same type.
Take the following scenario, for example, where we have catAnimal
and dogAnimal
beans, both belonging to the Animal
type:
@ClawjectApplication
class Application {
@Bean
catAnimal = new Animal('meow');
@Bean
dogAnimal = new Animal('woof');
@PostConstruct
postConstruct(
animal: Animal // <-- Which bean will be injected here?
) {}
}
In this case, if we attempt to compile application,
Clawject will report that two possible candidates found for animal parameter.
Normally, we can set argument name same as bean name, but what if we just need some any bean of type Animal?
To overcome this problem, Clawject provides the @Primary
decorator.
The @Primary
decorator can be used on Bean to indicate that
a Bean should be given preference when multiple beans of the same type are available.
@ClawjectApplication
class Application {
@Bean
@Primary
catAnimal = new Animal('meow');
@Bean
dogAnimal = new Animal('woof');
@PostConstruct
postConstruct(
animal: Animal // <-- catAnimal will be injected here
) {
console.log(animal.sound);
}
}
In this case, catAnimal
will be injected into the postConstruct
method because it is marked as @Primary
.
But if you want to inject dogAnimal
, even if catAnimal
is marked as @Primaru
you should specify parameter name of the dependency same as bean name.
@ClawjectApplication
class Application {
@Bean
@Primary
catAnimal = new Animal('meow');
@Bean
dogAnimal = new Animal('woof');
@PostConstruct
postConstruct(
dogAnimal: Animal // <-- dogAnimal will be injected here
) {
console.log(dogAnimal.sound);
}
}