使用Kotlin在HttpServlet中使用Guice依赖项注入

时间:2018-09-21 06:10:49

标签: java kotlin guice guice-servlet

我在将依赖项注入我的HttpServlet时遇到麻烦。如果使用构造函数注入,由于缺少空的构造函数(即使使用kotlin-noarg插件,也会收到servlet实例化错误)。如果我在@Inject上使用lateinit var,则会收到lateinit property name has not been initialized错误。我在做什么错了?

这是我的代码:

HomeController.kt

import com.google.inject.Inject
import com.google.inject.Singleton
import com.google.inject.name.Named
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Singleton
@WebServlet(name = "Hello", value = ["/hello"])
class HomeController: HttpServlet() {

    @Inject
    @Named("app-url")
    lateinit var name: String

    override fun doGet(req: HttpServletRequest, res: HttpServletResponse) {
        res.writer.write("Hello, $name!")
    }
}

MainModule.kt

class MainModule : Module {

    /**
     * Contributes bindings and other configurations for this module to `binder`.
     */
    override fun configure(binder: Binder) {
        val conf = ConfigFactory.load()

        binder.bind(String::class.java).annotatedWith(Names.named("app-url")).toInstance(conf.getString("appUrl")) // TODO: move to env

    }
}

MyGuiceServletConfig.kt

import com.google.inject.Guice
import com.google.inject.Injector
import com.google.inject.servlet.GuiceServletContextListener

class MyGuiceServletConfig : GuiceServletContextListener() {
    override fun getInjector(): Injector {
        return Guice.createInjector(
                MyServletModule(),
                MainModule()
        )
    }
}

MyServletModule.kt

class MyServletModule: ServletModule() {

    override fun configureServlets() {
        serve("/home").with(HomeController::class.java)
    }
}

webapp / WEB-INF / web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>tj.alif.core.app.guice.MyGuiceServletConfig</listener-class>
    </listener>
</web-app>

1 个答案:

答案 0 :(得分:0)

您已经尝试过吗?

@JvmField
@Inject
@Named("app-url")
lateinit var name: String

不幸的是,这只是一个猜测,因为我现在没有IDE。

相关问题