繁体   English   中英

使用注入的bean方法的返回值作为@Cacheable批注中的键

[英]Using Injected bean method return value as key in @Cacheable annotation

我的一个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();
}

}

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

使用Spring bean作为具有@Cacheable批注的键

我将编写此类,以便将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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM