I have an Spring Rest application, in which there's a requirement to get some access token in a service(Annotated with @Service
) class. The token generation is in a separate class(Annotated with @Component
) and the requirement given is to get a unique token for each new request. And I'll be using the generated token two times within the same request in the service class. Now the questions are as follows.
I can inject the tokenGenerator class using @Autowired
. And get the token, store it in the private instance variable inside the class and use it wherever I wanted inside the service class. Is it the correct approach to store a value that should live as long as the request is alive. When I tested this approach I find the same access token is printed across the methods in service class for a single request. what would go wrong here?
Another approach I tried was using WebApplicationContext.SCOPE_REQUEST
on the TokenGenerator class and use the Provider in my service class to get the class instance and then access token from it. This also works the same way as the previous approach. If so why do I even need to use the approach for request scoped values?
Approach 1: Here I have used the dependency injection to get the access token.
@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
}
Approach 2: Here I have used the RequestScope to get the access token. and Used the Provider to get the instance in the service class.
@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
}