Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Spring's @Cacheable annotation have the same scope as the annotated method's bean?

Tags:

java

spring

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.

like image 804
Max Nanasy Avatar asked Apr 14 '12 04:04

Max Nanasy


People also ask

What is @cacheable in spring boot?

@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.

How does Spring @cacheable work?

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.

What is global session scope?

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 .

Which is the spring boot annotation used for caching auto configuration?

Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation.


1 Answers

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.

like image 169
Bozho Avatar answered Sep 28 '22 12:09

Bozho