Qualifying By Name
To qualify by name you can use the Named annotation. For example, consider the following classes:
public interface Engine { (1)
int getCylinders();
String start();
}
@Singleton
public class V6Engine implements Engine { (2)
@Override
public String start() {
return "Starting V6";
}
@Override
public int getCylinders() {
return 6;
}
}
@Singleton
public class V8Engine implements Engine {
@Override
public String start() {
return "Starting V8";
}
@Override
public int getCylinders() {
return 8;
}
}
@Singleton
public class Vehicle {
private final Engine engine;
@Inject
public Vehicle(@Named("v8") Engine engine) {(4)
this.engine = engine;
}
public String start() {
return engine.start();(5)
}
}
interface Engine { (1)
int getCylinders()
String start()
}
@Singleton
class V6Engine implements Engine { (2)
int cylinders = 6
@Override
String start() {
"Starting V6"
}
}
@Singleton
class V8Engine implements Engine { (3)
int cylinders = 8
@Override
String start() {
"Starting V8"
}
}
@Singleton
class Vehicle {
final Engine engine
@Inject Vehicle(@Named('v8') Engine engine) { (4)
this.engine = engine
}
String start() {
engine.start() (5)
}
}
interface Engine { (1)
val cylinders: Int
fun start(): String
}
@Singleton
class V6Engine : Engine { (2)
override var cylinders: Int = 6
override fun start(): String {
return "Starting V6"
}
}
@Singleton
class V8Engine : Engine {
override var cylinders: Int = 8
override fun start(): String {
return "Starting V8"
}
}
@Singleton
class Vehicle @Inject
constructor(@param:Named("v8") private val engine: Engine)(4)
{
fun start(): String {
return engine.start()(5)
}
}
1 | The Engine interface defines the common contract |
2 | The V6Engine class is the first implementation |
3 | The V8Engine class is the second implementation |
4 | The javax.inject.Named annotation is used to indicate the V8Engine implementation is required |
5 | Calling the start method prints: “Starting V8” |
Micronaut is capable of injecting V8Engine
in the previous example, because:
@Named
qualifier value (v8
) + type being injected simple name (Engine
) == (case insensitive) == The simple name of a bean of type Engine
(V8Engine
)
You can also declare @Named at the class level of a bean to explicitly define the name of the bean.