有沒有使用Spring的@Cacheable
註解與非單(如會話範圍)bean並緩存具有相同的範圍,因爲說豆一種簡單的方法?Spring的@Cacheable註釋與註釋方法的bean有相同的作用域嗎?
實施例:
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
@Named
@Scope("session")
public class UserNameRetriever {
@Inject private UserDao userDao;
@Cacheable("userName")
public String getUserName() {
return userDao.getUserByLogin((String)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();
}
}
理想情況下,將UserNameRetriever.getUserName()
取從UserDao
每一次會話的用戶名,但是這個代碼實際上緩存應用程序範圍內。
此工作,但有內存泄漏而不 ( \t \ @CacheEvict(值= 「username」 的,鍵= 「#root.target」) \t \ @PreDestroy \t公共無效清理(){ \t} ) 另外,我已經決定不畢竟使用@Cacheable,因爲它不保證該值將只計算一次。 – 2012-04-16 19:28:54
內存泄漏是什麼意思?也許你的緩存太大了。 @Cacheable將首先在緩存中查找,因此它保證在仍處於緩存中時不會計算該值。 – sinuhepop 2012-04-16 19:59:46
這是內存泄漏,因爲一旦會話結束,該值仍在緩存中,但無法訪問。 @PreDestroy確保會話結束時緩存的值被清除。 – 2012-04-16 20:11:27