bean 是一个对象,其生命周期由 Micronaut IoC 容器管理。该生命周期可能包括创建、执行和销毁。 Micronaut 实现了 JSR-330 (javax.inject) - Java 规范的依赖注入,因此要使用 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 实现被定义并标记为单例范围
引擎通过构造函数注入注入
要执行依赖注入,请使用 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 自动发现类路径上的依赖注入元数据,并根据您定义的注入点将 bean 连接在一起。
Micronaut 支持以下类型的依赖注入:
更多建议: