【问题标题】:Using Injected bean method return value as key in @Cacheable annotation使用注入的 bean 方法返回值作为 @Cacheable 注释中的键
【发布时间】:2012-08-01 20:38:36
【问题描述】:

我的一个 bean 中有一个 @Cacheable 注释方法,我想使用当前登录的用户 ID 作为 Cache 的键。但是,我使用 Spring Security 并在此 bean 中有一个 Injected 服务作为实例变量,它调用 SecurityContextHolder.getContext().getAuthentication() 以返回用户 ID。因此,我在 @Cacheable 方法上有一个零参数构造函数。是否可以使用从我注入的服务方法返回的用户 ID 作为缓存的键?

@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();
}

}

我发现了这个问题,但它与我想做的有些不同。我认为静态方法无法实现此功能。

Using Spring beans as a key with @Cacheable annotation

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    我会编写这个类,以便 userId 是 getInformation() 方法的参数,并让方法/服务的用户自己通过查找 ID。

    @Override
    @Cacheable("myCache")
    public String getInformation(String userId) { ... }
    

    IMO 编写服务层以直接使用 Spring Security 上下文是一种不好的做法,因为它限制了服务的有用性 - 如果您实现某种不使用 Spring Security 的 REST API(就像例如),那么getCurrentUser() 可能没有意义/返回值。然后MyServiceImpl 不可用,如果 Spring Security 不用于该请求,并且如果您需要支持诸如“管理员用户需要查找用户 X 的信息”之类的内容,则此方法不可用。

    让面向 Web 的层担心如何从安全上下文中提取用户 ID,而不是您的服务层。

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 1970-01-01
      • 2018-05-06
      • 2013-06-26
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      相关资源
      最近更新 更多