依赖注入与请求范围

时间:2020-02-14 14:24:01

标签: java spring spring-mvc spring-rest requestscope

我有一个Spring Rest应用程序,其中需要在服务(用@Service注释)类中获得一些访问令牌。令牌生成在单独的类中(用@Component注释),给出的要求是为每个新请求获取唯一的令牌。我将在服务类的同一请求中两次使用生成的令牌。现在的问题如下。

我可以使用@Autowired注入tokenGenerator类。并获取令牌,将其存储在类内部的私有实例变量中,并在服务类中需要的任何地方使用它。这是一种正确的方法来存储一个只要请求仍然有效的值。当我测试这种方法时,我发现针对单个请求,在服务类中的方法之间会打印相同的访问令牌。这里怎么了?

我尝试的另一种方法是在TokenGenerator类上使用WebApplicationContext.SCOPE_REQUEST,并在我的服务类中使用Provider获取类实例,然后从中访问令牌。这也与以前的方法相同。如果是这样,为什么我什至需要对请求范围值使用该方法?

方法1: 在这里,我已经使用依赖注入来获取访问令牌。

@Component
public class TokenGenerator
{
 public string getToken();//okhttp Rest API Call
}

@Service
public class ServiceClass{
    @Autowired 
    TokenGenetor token;

    private String tokenValue;//**setTokenValue as setter**

    public void method1()
    {
     setTokenValue(token.getToken());
    }
    public method2(){print(tokenValue)}// prints 1234abcd
    public method3(){print(tokenValue)}// prints 1234abcd
}

方法2: 在这里,我使用RequestScope来获取访问令牌。并使用Provider在服务类中获取实例。

@Component
@scope(WebApplicationContext=scope_request)
public class TokenGenerator
{
    public string getToken();//okhttp Rest API Call
}

@Service
public class ServiceClass{
    @Autowired 
    private Provider<TokenGenetor> token;

    private String tokenValue;//setTokenValue as setter

    public void method1()
    {
     // Not Setting anything
    }
    public method2(){print(token.get().getToken();)}// prints 1234abcd
    public method3(){print(token.get().getToken();)}// prints 1234abcd
}

0 个答案:

没有答案