2012-08-03 92 views
0

我的一個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

回答

1

我會寫這個類,使得用戶id是一個參數傳遞給getInformation()方法,使方法/服務通的用戶查找的ID本身。

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

IMO這是一個不好的做法,寫你的服務層直接使用Spring Security的情況下,因爲它限制了服務的實用性 - 如果實現某種形式的REST API的不使用Spring Security (只是一個例子),那麼getCurrentUser()可能沒有意義/返回值。那麼MyServiceImpl是不可用的,如果Spring Security未用於該請求,並且如果您需要支持「管理用戶需要查找用戶X的信息」之類的東西,則此方法無法使用。

讓面向網絡的層擔心如何從安全上下文中提取用戶標識,而不是服務層。

相關問題