Qualifying By Name

To qualify by name you can use the Named annotation. For example, consider the following classes:

  1. public interface Engine { (1)
  2. int getCylinders();
  3. String start();
  4. }
  5. @Singleton
  6. public class V6Engine implements Engine { (2)
  7. @Override
  8. public String start() {
  9. return "Starting V6";
  10. }
  11. @Override
  12. public int getCylinders() {
  13. return 6;
  14. }
  15. }
  16. @Singleton
  17. public class V8Engine implements Engine {
  18. @Override
  19. public String start() {
  20. return "Starting V8";
  21. }
  22. @Override
  23. public int getCylinders() {
  24. return 8;
  25. }
  26. }
  27. @Singleton
  28. public class Vehicle {
  29. private final Engine engine;
  30. @Inject
  31. public Vehicle(@Named("v8") Engine engine) {(4)
  32. this.engine = engine;
  33. }
  34. public String start() {
  35. return engine.start();(5)
  36. }
  37. }
  1. interface Engine { (1)
  2. int getCylinders()
  3. String start()
  4. }
  5. @Singleton
  6. class V6Engine implements Engine { (2)
  7. int cylinders = 6
  8. @Override
  9. String start() {
  10. "Starting V6"
  11. }
  12. }
  13. @Singleton
  14. class V8Engine implements Engine { (3)
  15. int cylinders = 8
  16. @Override
  17. String start() {
  18. "Starting V8"
  19. }
  20. }
  21. @Singleton
  22. class Vehicle {
  23. final Engine engine
  24. @Inject Vehicle(@Named('v8') Engine engine) { (4)
  25. this.engine = engine
  26. }
  27. String start() {
  28. engine.start() (5)
  29. }
  30. }
  1. interface Engine { (1)
  2. val cylinders: Int
  3. fun start(): String
  4. }
  5. @Singleton
  6. class V6Engine : Engine { (2)
  7. override var cylinders: Int = 6
  8. override fun start(): String {
  9. return "Starting V6"
  10. }
  11. }
  12. @Singleton
  13. class V8Engine : Engine {
  14. override var cylinders: Int = 8
  15. override fun start(): String {
  16. return "Starting V8"
  17. }
  18. }
  19. @Singleton
  20. class Vehicle @Inject
  21. constructor(@param:Named("v8") private val engine: Engine)(4)
  22. {
  23. fun start(): String {
  24. return engine.start()(5)
  25. }
  26. }
1The Engine interface defines the common contract
2The V6Engine class is the first implementation
3The V8Engine class is the second implementation
4The javax.inject.Named annotation is used to indicate the V8Engine implementation is required
5Calling 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.