I have a service which caches the response. I use a simple Map for caching the response.
I also have two scopes: @RequestScope
and @GrpcScope
. @RequestScope
is obviously for requests received from rest controller whereas @GrpcScope
is for grpc requests.
My service doesn't know what scope it is currently running in. Both (grpc and rest) controllers uses the same service and there could be only one scope active at runtime.
I want FooService
to use RequestScopedFooCache
in if the the scope is @RequestScope
and to use GrpcScopedFooCache
if the scope is @GrpcScope
. How can I do that?
// for RequestScope
@RestController
public class FooRestController{
@Autowired
FooService fooService;
@GetMapping
public BarResponse getFoo(){
return fooService.fooRequest(...)
}
}
// for @GrpcScope
@GrpcController
public class FooGrpcController{
@Autowired
FooService fooService;
public BarResponse getFoo(){
return fooService.fooRequest(...)
}
}
@Service
public class FooService {
@Autowired
FooCache cache; // doesn't know which bean to autowire however there could be only one of them at runtime
BarResponse fooRequest(String id) {
if(cache.get(id))
...
}
}
public interface FooCache {
...
}
@Component
@RequestScope
public class RequestScopedFooCache implements FooCache {
...
}
@Component
@GrpcScope
public class GrpcScopedFooCache implements FooCache {
...
}
Using SpringBoot version 2.4.+