我的一個bean中有一個@Cacheable註解方法,我想使用當前登錄的用戶ID作爲Cache的關鍵字。然而,我使用Spring Security並在此Bean中有一個Injected服務作爲實例變量,它調用SecurityContextHolder.getContext()。getAuthentication()返回用戶ID。因此,我在@Cacheable方法上有一個零參數構造函數。無論如何,使用從我的注入服務的方法返回的用戶ID作爲Cache的關鍵字?使用Injected bean方法返回值作爲@Cacheable註釋中的鍵
@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