gpt4 book ai didi

java - 为什么需要实现一个在手动播种值时抛出异常的提供程序?

转载 作者:行者123 更新时间:2023-11-30 06:52:48 25 4
gpt4 key购买 nike

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

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

您可以实现自定义过滤器来种子值稍后注入(inject),例如

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

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

绑定(bind)可能如下所示:

  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 的依赖项,但没有提供程序,甚至无法创建注入(inject)器。它需要能够提前将每个依赖项连接到提供者。

关于java - 为什么需要实现一个在手动播种值时抛出异常的提供程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42415195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com