使用Injectedbean方法返回值作为@Cacheable注释中的键



我的一个bean中有一个@Cacheable注释方法,我想使用当前登录的用户ID作为Cache的键。然而,我使用的是Spring Security,并且在这个bean中有一个Injected服务作为实例变量,它调用SecurityContextHolder.getContext().getAuthentication()来返回用户ID。因此,我在@Cacheable方法上有一个零参数构造函数。是否可以使用从我注入的服务的方法返回的用户ID作为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实现:

@Service
public class UserContextServiceImpl implements UserContextService {
public String getCurrentUser() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
}

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

使用Springbeans作为带有@Cacheable annotation 的密钥

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

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

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

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

最新更新