【问题标题】:Using Guice dependency injection in HttpServlet with Kotlin在 HttpServlet 和 Kotlin 中使用 Guice 依赖注入
【发布时间】:2018-09-21 06:10:48
【问题描述】:

我无法将依赖项注入我的HttpServlet。如果我使用构造函数注入,我会得到 servlet 实例化错误,因为没有空构造函数(即使我使用 kotlin-noarg 插件)。如果我在lateinit var 上使用@Inject,我会得到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>

【问题讨论】:

    标签: java kotlin guice guice-servlet


    【解决方案1】:

    你已经试过了吗?

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多