シングルトンではない(たとえば、セッションスコープの)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();
}
}
理想的には、セッションごとに1回UserNameRetriever.getUserName()
からユーザー名をフェッチしますが、このコードは実際にはアプリケーション全体をキャッシュします。UserDao