Is there an easy way to use Spring's @Cacheable
annotation with a non-singleton (e.g. session-scoped) bean and have the cache have the same scope as said bean?
Example:
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();
}
}
Ideally, UserNameRetriever.getUserName()
would fetch the username from the UserDao
once per session, but this code actually caches application-wide.
@CacheableThis method-level annotation lets Spring Boot know that the return value of the annotated method can be cached. Each time a method marked with this @Cacheable is called, the caching behavior will be applied.
As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.
global session. Scopes a single bean definition to the lifecycle of a global HTTP Session . Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext .
Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation.
If you want a session cache, use the session. That is, store the user in a private field in the session-scoped bean, or access the HttpSession
object directly. @Cacheable
is generally meant for application-wide resources.
Well, you can use key="#user.id"
, and to invalidate the cache (manually or with @CacheEvict
) on a @PreDestroy
method, but it would be better if you don't mix the two - caching and session data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With