oztimpower
oztimpower

Reputation: 31

Quarkus Kotlin Inject failure

The @Inject annotation for a service, defined by "@ApplicationScope" fails to inject in Kotlin.

"kotlin.UninitializedPropertyAccessException: lateinit property greeter has not been initialized"

The explanation on similar question: "This problem results as a combination of how Kotlin handles annotations and the lack of the a @Target on the ... annotation definition. Add @field: xxx"

Question is, how do I make this work for a service injection?

import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import javax.enterprise.context.ApplicationScoped
import javax.inject.Inject


class HelloRequest() {
    var firstName: String? = null
    var lastName: String? = null
}

@ApplicationScoped
open class HelloGreeter() {
    open fun greet(firstName: String?, lastName: String?): String {
        return "$firstName, $lastName"
    }
}

class HelloLambda : RequestHandler<HelloRequest, String> {

    @Inject
    lateinit var greeter: HelloGreeter

    override fun handleRequest(request: HelloRequest, context: Context): String {
        return greeter.greet(request.firstName, request.lastName)
    }
}

Similar questions: "This problem results as a combination of how Kotlin handles annotations and the lack of the a @Target on the ... annotation definition. Add @field: xxx"

  • Error to inject some dependency with kotlin + quarkus
  • SmallRye Reactive Messaging's Emitter<>.send doesn't send in Kotlin via AMQP broker with Quarkus

    Upvotes: 0

    Views: 832

  • Answers (1)

    oztimpower
    oztimpower

    Reputation: 31

    I tested the modified, @field: xx with a standard rest service, and by qualifying it with @field: ApplicationScoped, it does now work.

    The answer to my question above would be then that there is no runtime CDI when using the Quarkus Amazon Lambda extension.

    import javax.enterprise.context.ApplicationScoped
    import javax.inject.Inject
    import javax.ws.rs.GET
    import javax.ws.rs.Path
    import javax.ws.rs.PathParam
    import javax.ws.rs.Produces
    import javax.ws.rs.core.MediaType
    
    
    @ApplicationScoped
    open class GreetingService2 {
    
        fun greeting(name: String): String {
            return "hello $name"
        }
    
    }
    
    @Path("/")
    class GreetingResource {
    
        @Inject
        @field: ApplicationScoped
        lateinit var service: GreetingService2
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        @Path("/greeting/{name}")
        fun greeting(@PathParam("name") name: String): String {
            return service.greeting(name)
        }
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        fun hello(): String {
            return "hello"
        }
    }
    

    Upvotes: 2

    Related Questions