Guice Servlets的简单示例

Rob*_*ert 8 java model-view-controller dependency-injection guice

我不知道如何处理一个简单的guice示例.阅读完文档后,我完成了以下工作:

  • 设置guiceFilter
  • 创建了一个注入器并在a中实例化了一个新的ServletModule GuiceServletContextListener,并将该侦听器添加到web.xml中
  • 绑定serve("*.jsp").with(IndexController.class);在配置servlet中

在我完成之后如何使用依赖注入?假设我有一个index.jsp,IndexController.class(s​​ervlet),以及两个名为Person和Order with Person的类,具体取决于Order.如何通过guice将Order依赖注入到Person构造函数中,在我这样做之后,我需要返回说这个人的命令列表回到控制器?我过去使用过Ninject和ASP.NET MVC,这很简单,但我对如何用Guice实现最简单的DI示例感到很困惑.谢谢.

Dav*_*ton 23

首先,这是一个注入服务的示例,该服务将名称列表返回到索引控制器中.(在这个例子中没有任何诡计,一切都是明确的.)

ListService interface定义了简单的服务.

public interface ListService {
    List<String> names();
}
Run Code Online (Sandbox Code Playgroud)

DummyListService 提供简单的实现.

public class DummyListService implements ListService {
    public List<String> names() {
        return Arrays.asList("Dave", "Jimmy", "Nick");
    }
}
Run Code Online (Sandbox Code Playgroud)

ListModule连线ListService到虚拟实现.

public class ListModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(ListService.class).to(DummyListService.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

GuiceServletContextListener实现将servlet映射到索引,并创建ListModule如上所述.

@Override
protected Injector getInjector() {
    return Guice.createInjector(
            new ServletModule() {
                @Override protected void configureServlets() {
                    serve("/index.html").with(IndexController.class);
                }
            },
            new ListModule());
}
Run Code Online (Sandbox Code Playgroud)

IndexController 将名称放入请求范围(手动)并转发到JSP页面.

@Singleton
public class IndexController extends HttpServlet {

    @Inject ListService listService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("names", listService.names());
        req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp);
    }

}
Run Code Online (Sandbox Code Playgroud)

JSP页面转储名称(仅限片段).

<c:forEach items="${names}" var="name">
  ${name}<br/>
</c:forEach>
Run Code Online (Sandbox Code Playgroud)