为什么有必要实现一个在手动设置值时抛出异常的提供程序?

时间:2017-02-23 12:00:52

标签: java dependency-injection guice

在使用google guice时,我遇到了有关如何在请求范围内手动设置值的文档。

[https://github.com/google/guice/wiki/ServletModule#dispatch-order]

您可以实现自定义过滤器,以便为稍后注入的值设定种子,例如

   protected Filter createUserIdScopingFilter() {
     return new Filter() {
       @Override public void doFilter(
          ServletRequest request,  ServletResponse response, FilterChain chain)
           throws IOException, ServletException {
         HttpServletRequest httpRequest = (HttpServletRequest) request;
         // ...you'd probably want more sanity checking here
         Integer userId = Integer.valueOf(httpRequest.getParameter("user-id"));
         httpRequest.setAttribute(
             Key.get(Integer.class, Names.named("user-id")).toString(),
             userId);  
         chain.doFilter(request, response);
       }

      @Override public void init(FilterConfig filterConfig) throws ServletException { }

      @Override public void destroy() { }
     };
  } 

在本文档中,他们将绑定解释为

绑定可能如下所示:

  public class YourServletModule extends ServletModule {
     @Override protected void configureServlets() {
         .....
        filter("/process-user*").through(createUserIdScopingFilter());
    }

    @Provides @Named("user-id") @RequestScoped Integer provideUserId() {
      throw new IllegalStateException("user id must be manually seeded");
    }
  }

我想了解为什么有必要实现抛出异常的提供方法?它的目的是什么?

0 个答案:

没有答案