java - 使用注入(inject)的bean方法返回值作为@Cacheable注释中的键

标签 java spring spring-security

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

}

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

Using Spring beans as a key with @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 的层关心如何从安全上下文中提取用户 ID,而不是您的服务层。

关于java - 使用注入(inject)的bean方法返回值作为@Cacheable注释中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11801786/

相关文章:

java - 如何使用 RxJava 和 Spring 进行批量保存

spring-security - 运行 JUnit 测试时,Spring Security 不调用我的自定义身份验证过滤器

java - 找出给定 Java 进程的 -Xms 和 -Xmx 变量值的命令?

spring - *.configuration.SecondaryDataSource 中方法 entityManagerFactory 的参数 0 需要找不到类型为 '*.EntityManagerFactoryBuilder' 的 bean

javascript - 在ajax请求中获取Spring @RequestParam

java - 部署 Web 应用程序后出现“连接过多”错误

spring - 为什么 AuthenticationManager 会抛出 StackOverflowError?

java - Spring Data Rest存储库的安全方法

java - enums value() 方法和 class.getEnumConstants() 的比较

java - 如何在 Antlr4 中为零参数函数编写语法