我的一个 bean 中有一个带有 @Cacheable 注释的方法,我想使用当前登录的用户 ID 作为缓存的键。但是,我使用 Spring Security 并在该 bean 中将注入(inject)服务作为实例变量,调用 SecurityContextHolder.getContext().getAuthentication() 以返回用户 ID。因此,我在 @Cacheable 方法上有一个零参数构造函数。无论如何,是否可以使用从我注入(inject)的服务方法返回的用户 ID 作为缓存的 key ?
@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 实现:
@Service
public class UserContextServiceImpl implements UserContextService {
public String getCurrentUser() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
}
我发现了这个问题,但它与我想要做的有些不同。我认为静态方法不可能实现此功能。
最佳答案
我会编写此类,以便将 userId 作为 getInformation()
方法的参数,并使该方法/服务的用户自行查找 ID。
@Override
@Cacheable("myCache")
public String getInformation(String userId) { ... }
IMO,编写服务层直接使用 Spring Security 上下文是一种不好的做法,因为它限制了服务的有用性 - 如果您实现某种不使用 Spring Security 的 REST API(就像例如),那么 getCurrentUser()
可能没有任何意义/返回值。如果 Spring Security 未用于该请求,那么 MyServiceImpl 就无法使用,并且如果您需要支持诸如“管理员用户需要查找用户 X 的信息”之类的内容,则此方法将无法使用。
让面向 Web 的层关心如何从安全上下文中提取用户 ID,而不是您的服务层。
关于java - 使用注入(inject)的bean方法返回值作为@Cacheable注释中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11801786/