bean 是一個對象,其生命周期由 Micronaut IoC 容器管理。該生命周期可能包括創(chuàng)建、執(zhí)行和銷毀。 Micronaut 實現(xiàn)了 JSR-330 (javax.inject) - Java 規(guī)范的依賴注入,因此要使用 Micronaut,您只需使用 javax.inject 提供的注釋。
下面是一個簡單的例子:
Java |
Groovy |
Kotlin |
public interface Engine { // (1)
int getCylinders();
String start();
}
@Singleton// (2)
public class V8Engine implements Engine {
private int cylinders = 8;
@Override
public String start() {
return "Starting V8";
}
@Override
public int getCylinders() {
return cylinders;
}
public void setCylinders(int cylinders) {
this.cylinders = cylinders;
}
}
@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
@Override
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()
}
}
|
定義了一個通用引擎接口
V8Engine 實現(xiàn)被定義并標記為單例范圍
引擎通過構(gòu)造函數(shù)注入注入
要執(zhí)行依賴注入,請使用 run() 方法運行 BeanContext 并使用 getBean(Class) 查找 bean,如下例所示:
Java |
Groovy |
Kotlin |
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 自動發(fā)現(xiàn)類路徑上的依賴注入元數(shù)據(jù),并根據(jù)您定義的注入點將 bean 連接在一起。
Micronaut 支持以下類型的依賴注入:
更多建議: