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

why is it necessary to implement a provider that throws exception when you manually seed a value?

在使用 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");
    }
  }

我想了解为什么需要实现一个抛出异常的 provides 方法?它的目的是什么?

Guice 中的作用域是通过获取 Provider 并将其包装在新的 Provider 中实现的:https://google.github.io/guice/api-docs/4.1/javadoc/com/google/inject/Scope.html#scope-com.google.inject.Key-com.google.inject.Provider-

必须要包装一些初始提供程序,即使它没有做任何有用的事情。

事实上,如果您从模块中省略提供程序,Guice 将找到对 @Named("user-id") Integer 的依赖项,但没有它的提供程序,甚至无法创建注入器。它需要能够提前将每个依赖项连接到提供程序。