java - 如何使用 ServletScopes.scopeRequest() 和 ServletScopes.continueRequest()?

标签 java guice

  1. 应该如何使用 ServletScopes.scopeRequest()
  2. 如何在 Callable 中获取对 @RequestScoped 对象的引用?
  3. seedMap 有什么意义?是否意味着覆盖默认绑定(bind)?
  4. 这个方法和ServletScopes.continueRequest()有什么区别? ?

最佳答案

回答我自己的问题:

  1. ServletScopes.scopeRequest() 请求范围内运行 Callable。请注意不要跨不同范围引用对象,否则您最终会遇到线程问题,例如尝试使用已被另一个请求关闭的数据库连接。 static或顶级类(class)是您的 friend 。
  2. 您注入(inject) Callable在将其传递给 ServletScopes.scopeRequest() 之前.出于这个原因,你必须小心你的 Callable 的字段。包含。更多内容请见下文。
  3. seedMap允许您将非作用域 对象注入(inject)作用域。这很危险,所以要小心你注入(inject)的东西。
  4. ServletScopes.continueRequest()除了它在 existing 请求范围内运行外,它是相似的。它获取当前 HTTP 范围的快照并将其包装在 Callable 中。原始 HTTP 请求完成(您从服务器返回一些响应)但随后在单独的线程中异步完成实际操作。当稍后调用 Callable 时(在那个单独的线程中),它将可以访问原始 HttpServletRequest 但不能访问 HTTP 响应或 session 。

那么,最好的方法是什么?

如果您不需要将用户对象传递到 Callable :注入(inject) Callable超出请求范围,传入ServletScopes.scopeRequest() . Callable可能只引用Provider<Foo>而不是 Foo ,否则您最终会在请求范围之外注入(inject)实例。

如果您需要将用户对象传递到 Callable ,请继续阅读。

假设您有一个将名称插入数据库的方法。我们有两种方法可以将名称传递给 Callable .

方法 1:使用子模块传递用户对象:

  1. 定义 InsertName , 一个 Callable插入数据库:

    @RequestScoped
    private static class InsertName implements Callable<Boolean>
    {
      private final String name;
      private final Connection connection;
    
      @Inject
      public InsertName(@Named("name") String name, Connection connection)
      {
        this.name = name;
        this.connection = connection;
      }
    
      @Override
      public Boolean call()
      {
        try
        {
          boolean nameAlreadyExists = ...;
          if (!nameAlreadyExists)
          {
            // insert the name
            return true;
          }
          return false;
        }
        finally
        {
          connection.close();
        }
      }
    }
    
  2. 在子模块中绑定(bind)所有用户对象,并使用 RequestInjector.scopeRequest() 确定可调用对象的范围:

    requestInjector.scopeRequest(InsertName.class, new AbstractModule()
    {
      @Override
      protected void configure()
      {
        bind(String.class).annotatedWith(Names.named("name")).toInstance("John");
      }
    })
    
  3. 我们实例化一个 RequestInjector在请求之外,它又注入(inject)第二个 Callable 请求中。第二个Callable可以引用Foo直接(不需要提供者),因为它被注入(inject)到请求范围内。

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.servlet.ServletScopes;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Injects a Callable into a non-HTTP request scope.
 * <p/>
 * @author Gili Tzabari
 */
public final class RequestInjector
{
    private final Map<Key<?>, Object> seedMap = Collections.emptyMap();
    private final Injector injector;

    /**
     * Creates a new RequestInjector.
     */
    @Inject
    private RequestInjector(Injector injector)
    {
        this.injector = injector;
    }

    /**
     * Scopes a Callable in a non-HTTP request scope.
     * <p/>
     * @param <V> the type of object returned by the Callable
     * @param callable the class to inject and execute in the request scope
     * @param modules additional modules to install into the request scope
     * @return a wrapper that invokes delegate in the request scope
     */
    public <V> Callable<V> scopeRequest(final Class<? extends Callable<V>> callable,
        final Module... modules)
    {
        Preconditions.checkNotNull(callable, "callable may not be null");

        return ServletScopes.scopeRequest(new Callable<V>()
        {
            @Override
            public V call() throws Exception
            {
                return injector.createChildInjector(modules).getInstance(callable).call();
            }
        }, seedMap);
    }
}

方法 2:注入(inject) Callable在引用 Provider<Foo> 的请求之外. call()然后方法可以get()请求范围内的实际值。 object 对象通过 seedMap 传入。 (我个人认为这种方法违反直觉):

  1. 定义 InsertName , 一个 Callable插入数据库。请注意,与方法 1 不同,我们必须使用 Providers :

    @RequestScoped
    private static class InsertName implements Callable<Boolean>
    {
      private final Provider<String> name;
      private final Provider<Connection> connection;
    
      @Inject
      public InsertName(@Named("name") Provider<String> name, Provider<Connection> connection)
      {
        this.name = name;
        this.connection = connection;
      }
    
      @Override
      public Boolean call()
      {
        try
        {
          boolean nameAlreadyExists = ...;
          if (!nameAlreadyExists)
          {
            // insert the name
            return true;
          }
          return false;
        }
        finally
        {
          connection.close();
        }
      }
    }
    
  2. 为您要传入的类型创建虚假绑定(bind)。如果您不这样做,您将得到:No implementation for String annotated with @com.google.inject.name.Named(value=name) was bound. https://stackoverflow.com/a/9014552/14731解释为什么需要这样做。

  3. 用所需的值填充 seedMap:

    ImmutableMap<Key<?>, Object> seedMap = ImmutableMap.<Key<?>, Object>of(Key.get(String.class, Names.named("name")), "john");
    
  4. 调用 ServletScopes.scopeRequest() :

    ServletScopes.scopeRequest(injector.getInstance(InsertName.class), seedMap);
    

关于java - 如何使用 ServletScopes.scopeRequest() 和 ServletScopes.continueRequest()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8402012/

相关文章:

java - 注册期间用于密码检查的简单正则表达式是什么?

java - java如何处理按位运算符的结果

java - 使用属性名称中的变量调用 bean 属性

java - 使用 Hibernate、Postgres 和 Guice Provider 时“事务中空闲”

guice - 通过注解动态生成注入(inject)

java - 在其模块中访问 Guice 注入(inject)器?

java 正则表达式,除字母字符/字符串之外的所有内容

java - Spring data - 修改查询并发

scala - 自定义操作中的依赖注入(inject) API

java - 如何为接口(interface)的实现创建多个实例?