Consider the following example:
String color()
}
interface ColorPicker {
fun color(): String
}
Given a common interface called ColorPicker
that is implemented by multiple classes.
The Primary Bean
import io.micronaut.context.annotation.Primary;
import javax.inject.Singleton;
@Primary
@Singleton
class Green implements ColorPicker {
@Override
public String color() {
return "green";
}
}
The Primary Bean
import io.micronaut.context.annotation.Primary
import javax.inject.Singleton
@Primary
@Singleton
class Green: ColorPicker {
override fun color(): String {
return "green"
}
The Green
bean is a ColorPicker
, but is annotated with @Primary
.
Another Bean of the Same Type
@Singleton
public class Blue implements ColorPicker {
@Override
public String color() {
return "blue";
}
}
import javax.inject.Singleton
@Singleton
class Blue implements ColorPicker {
@Override
String color() {
return "blue"
}
}
Another Bean of the Same Type
The Blue
bean is also a ColorPicker
and hence you have two possible candidates when injecting the ColorPicker
interface. Since Green
is the primary it will always be favoured.
@Controller("/testPrimary")
public class TestController {
protected final ColorPicker colorPicker;
public TestController(ColorPicker colorPicker) { (1)
@Get
public String index() {
return colorPicker.color();
}
}
@Controller("/test")
class TestController {
protected final ColorPicker colorPicker
TestController(ColorPicker colorPicker) { (1)
this.colorPicker = colorPicker
}
@Get
String index() {
colorPicker.color()
}
}
@Controller("/test")
class TestController(val colorPicker: ColorPicker) { (1)
@Get
fun index(): String {
return colorPicker.color()
}
If multiple possible candidates are present and no @Primary
is defined then a will be thrown.