The following is a simple example:
int getCylinders()
String start()
}
@Singleton (2)
class V8Engine implements Engine {
int cylinders = 8
String start() {
"Starting V8"
}
@Singleton
class Vehicle {
final Engine engine
Vehicle(Engine engine) { (3)
this.engine = engine
}
String start() {
}
}
To perform dependency injection simply run the using the run()
method and lookup a bean using getBean(Class)
, as per the following example:
final BeanContext context = BeanContext.run();
Vehicle vehicle = context.getBean(Vehicle.class);
System.out.println(vehicle.start());
val context = BeanContext.run()
val vehicle = context.getBean(Vehicle::class.java)
println(vehicle.start())
Micronaut supports the following types of dependency injection:
Constructor injection (must be one public constructor or a single contructor annotated with
@Inject
)JavaBean property injection