I have an @Cacheable annotated method in one of my beans, and I'd like to use the currently logged in user ID as the key for the Cache. However, I'm using Spring Security and have an Injected service as an instance variable in this bean that calls SecurityContextHolder.getContext().getAuthentication() to return the user ID. Hence, I have a zero-argument constructor on the @Cacheable method. Is there anyway to use the user ID returned from my injected service's method as the key for the Cache?
@Service
public class MyServiceImpl implements MyService {
@Inject
private UserContextService userContextService;
@Override
@Cacheable("myCache")
public String getInformation() {
//use this as the key for the cache entry
String userId = userContextService.getCurrentUser();
return "something";
}
}
UserContextService implementation:
@Service
public class UserContextServiceImpl implements UserContextService {
public String getCurrentUser() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
}
I found this question, but it's somewhat different from what I'd like to do. I don't think this functionality is possible with a static method.