Spring的@Cacheable注释是否与注释方法的bean具有相同的范围?

Max*_*asy 7 java spring

是否有一种简单的方法可以将Spring的@Cacheable注释与非单例(例如会话范围的)bean一起使用,并且缓存与所述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();
    }

}
Run Code Online (Sandbox Code Playgroud)

理想情况下,UserNameRetriever.getUserName()会从UserDao每个会话中获取一次用户名,但此代码实际上会缓存应用程序范围内的用户名.

Boz*_*zho 5

如果您需要会话缓存,请使用会话。即,将用户存储在会话作用域 bean 中的私有字段中,或者HttpSession直接访问对象。@Cacheable通常用于应用程序范围的资源。

好吧,您可以使用key="#user.id", 并使方法上的缓存无效(手动或使用@CacheEvict@PreDestroy,但如果不混合使用缓存和会话数据这两者会更好。


sin*_*pop 2

我还没有尝试过,但根据Spring 参考,我认为这会起作用:

@Cacheable(value = "userName", key = "#root.target")
Run Code Online (Sandbox Code Playgroud)