使用@Inject 注释的依赖注入如何在 micronaut Kotlin 中工作?

How Dependency injection with @Inject annotation works in micronaut Kotlin?

如何使用 micronaut 框架的 @Inject 注释在 class 中注入依赖项

@Controller("/")
class HelloController(val greetService:GreetService){

 @Get("/hello")
 fun getMessage(){
    greetService.greet 
  }

}

class GreetService(val userRepo:UserRepo){

  fun doSomething(val data:String){
      userRepo.saveData(data)
  } 
}
class UserRepo(val db:DbHandler){
     fun saveData(val data){
       db.save(data)
     }
}

如何使用@Inject

这没什么不同,你可以这样写:

@Inject
var greetingService:GreetingService;

或者您可以在构造函数上完成

class HelloController(@Inject val greetService:GreetService)

我更喜欢第二个选项,因为它使用 val 而不是 var。

 @Singleton
 class GreetService(val userRepo:UserRepo){

 fun doSomething(val data:String){
  userRepo.saveData(data)
     } 
   }

您要注入的 bean 必须按照 Micronaut 使用提供的注释(例如 @Singleton、@Context、@ThreadLocal 等)声明为 bean