3.1 Defining Beans
A bean is an object that has its lifecycle controlled by the Micronaut IoC container. That lifecycle may include creation, execution, and destruction. Micronaut implements the JSR-330 (javax.inject) - Dependency Injection for Java specification hence to use Micronaut you simply use the annotations provided by javax.inject.
The following is a simple example:
public interface Engine { (1)
int getCylinders();
String start();
}
@Singleton(2)
public class V8Engine implements Engine {
public String start() {
return "Starting V8";
}
public int getCylinders() {
return cylinders;
}
public void setCylinders(int cylinders) {
this.cylinders = cylinders;
}
private int cylinders = 8;
}
@Singleton
public class Vehicle {
private final Engine engine;
public Vehicle(Engine engine) {(3)
this.engine = engine;
}
public String start() {
return engine.start();
}
}
interface Engine { (1)
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() {
engine.start()
}
}
interface Engine {
(1)
val cylinders: Int
fun start(): String
}
@Singleton(2)
class V8Engine : Engine {
override var cylinders = 8
override fun start(): String {
return "Starting V8"
}
}
@Singleton
class Vehicle(private val engine: Engine)(3)
{
fun start(): String {
return engine.start()
}
}
1 | A common Engine interface is defined |
2 | A V8Engine implementation is defined and marked with Singleton scope |
3 | The Engine is injected via constructor injection |
To perform dependency injection simply run the BeanContext 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());
def context = BeanContext.run()
Vehicle vehicle = context.getBean(Vehicle)
println( vehicle.start() )
val context = BeanContext.run()
val vehicle = context.getBean(Vehicle::class.java)
println(vehicle.start())
Micronaut will automatically discover dependency injection metadata on the classpath and wire the beans together according to injection points you define.
Micronaut supports the following types of dependency injection:
Constructor injection (must be one public constructor or a single contructor annotated with
@Inject
)Field injection
JavaBean property injection
Method parameter injection