2017-03-29 72 views
2

我正在寫一個使用Guice作爲我的DI框架和Hibernate作爲我的Orm的java應用程序。我想運行一個簡單的嵌入式Jetty服務器來提供幾個jsp頁面。我設法使用下面的代碼來運行服務器:JSP bean中的Guice注入

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(); 

現在我想用幾個簡單的豆在我的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 
} 

缺少什麼我實現我的目標是什麼?

+0

我不認爲你可以。如果你想在JSP中使用DI,你需要使用Java EE的CDI框架。除非你想讓你自己的JSP標籤調用一個工廠直接傳遞給Guice注入器來獲取實例。 (請注意,這絕對是一個黑客,而不是一個好的)。 –

+0

感謝您的回覆,我終於找到了解決方案,看到我的答案在下面! – Duom

回答

1

我設法找到解決我的問題。我設法清理了我的意圖,並使用正確的技術重新啓動我的開發人員。

我從JSP切換到JSF2,我創建了吉斯噴射器工廠類:

public class GuiceFactory { 

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

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

然後在我的豆子的每個構造我打電話:

GuiceFactory.getInjector().injectMembers(this); 

不要猶豫,如果我的解決方案在設計或架構方面是錯誤的,請留言。