JSP bean 中的 Guice 注入

Guice injection in JSP bean

我正在编写一个 java 应用程序,使用 Guice 作为我的 DI 框架并使用 Hibernate 作为我的 Orm。我想 运行 一个简单的嵌入式 Jetty 服务器来服务几个 jsp 页面。我设法 运行 使用以下代码的服务器:

Server server = new Server(8081);
final WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/rpga");
webAppContext.setResourceBase("web/WEB-INF/");
webAppContext.setDescriptor("web/WEB-INF/web.xml");
webAppContext.setParentLoaderPriority(true);

final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration","org.eclipse.jetty.annotations.AnnotationConfiguration");

webAppContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/[^/]*servlet-api-[^/]*\.jar$|.*/javax.servlet.jsp.jstl-.*\.jar$|.*/[^/]*taglibs.*\.jar$|.*/classes/.*");

webAppContext.setServer(server);

server.setHandler(webAppContext);
server.start();
server.join();

我现在想使用几个简单的 bean 在我的 jsp 中添加一些数据。我尝试创建一个 bean 并将我的 dao 注入其中,但是由于该 bean 不是由 Guice 管理的,所以 Dao 没有被注入。

我的JSP长得像

<html>
   <head>
      <title>Playlist</title>
   </head>
   <body>
        <jsp:useBean id="playlist" class="com.duom.beans.PlaylistBean" /> 
        ...do stuff with playlistBean
   </body>
</html>

还有我的豆子:

import com.google.inject.Inject;

public class PlaylistBean {

    @Inject
    private PlaylistDao playlistDao;

    ...do stuff
}

我缺少什么来实现我的目标?

我设法找到了解决问题的办法。我设法清除了我的意图并使用正确的技术重新启动我的开发人员。

我从 JSP 切换到 JSF2,我为 Guice 注入器创建了一个工厂 class :

public class GuiceFactory {

    private static final Injector injector = Guice.createInjector(new RpgaAppModule());

    public static Injector getInjector() {
        return injector;
    }
}

然后在我的 bean 的每个构造函数上调用:

GuiceFactory.getInjector().injectMembers(this);

如果我的解决方案在设计或架构方面有误,请随时发表评论。