2014-10-09 69 views
3

我需要將什麼添加到contextInitialized方法才能正確初始化對象圖?如何用匕首初始化Web應用程序?

鑑於這把匕首模塊:

@Module 
public class MapperModule { 

    @Provides 
    @Singleton 
    ObjectMapper provideObjectMapper() { 
     return new ObjectMapper(); 
    } 

} 

了ServletContextListener的子類:

public class DaggerDi implements ServletContextListener { 

    @Override 
    public void contextInitialized(ServletContextEvent sce) { 
     ObjectGraph objectGraph = ObjectGraph.create(new MapperModule());     
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) { 

    } 

} 

而且在web.xml

<web-app> 
    <display-name>Archetype Created Web Application</display-name> 
    <listener> 
    <listener-class> 
      com.me.config.DaggerDi 
     </listener-class> 
    </listener> 
</web-app> 

回答

0

您可以檢查this dagger-servlet project,我還沒有嘗試過但是,看起來很簡單,你將不得不:

  1. 配置Servlet(web.xml文件):
<web-app> 
    <listener> 
     <listener-class>com.example.MyServletContextListener</listener-class> 
    </listener> 
    <filter> 
     <filter-name>Dagger Filter</filter-name> 
     <filter-class>com.leacox.dagger.servlet.DaggerFilter</filter-class> 
    </filter> 
    <filter-mapping> 
     <filter-name>Dagger Filter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 
</web-app> 
  • 實現一個上下文偵聽和模塊:

    @ Module(injects = {...},包含= ServletModule.class) public class MyModule {}

    @Module(=內噴射{...},包含= ServletRequestModule.class) 公共類MyRequestModule {}

    公共類MyServletContextListener延伸DaggerServletContextListener { @覆蓋 保護等級[] getBaseModules(){ 返回新類[] {MyModule.class}; }

    @Override 
    protected Class<?>[] getRequestScopedModules() { 
        return new Class<?>[]{MyRequestModule.class}; 
    } 
    

    }

  • 商祺!