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

Viewed 6414

how to inject dependencies in class with @Inject annotation for micronaut framework

@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)
     }
}

how to use @Inject

2 Answers

It's not any different you can write something like this :

@Inject
var greetingService:GreetingService;

Or you could do it on the constructor

class HelloController(@Inject val greetService:GreetService)

I prefer the second option because it uses val over var.

 @Singleton
 class GreetService(val userRepo:UserRepo){

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

the bean you want to inject has to be declared as bean as per Micronaut using provided annotations such as @Singleton , @Context ,@ThreadLocal etc

Related