简体   繁体   中英

Spring : Spring-cache not working

I am working on a Spring-MVC application. After the profiler went through the backend, I noticed that getCurrentlyAuthenticatedUser() is an hotspot. For the reason I thought of using cache. Unfortunately it is not working. Once the user logs in, I am getting null user, even though the user is logged in. What is going wrong. Ofcourse when I remove the @Cacheable annotation and config from XML, everything works fine. Any help would be nice.

PersonServiceImpl :

@Service
@Transactional
public class PersonServiceImpl implements PersonService {

  private final PersonDAO personDAO;

   @Autowired
    public PersonServiceImpl(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }
 @Override
    @Cacheable(value = "person", condition = "#person == null")
    public Person getCurrentlyAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        } else {
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }
}

config for using cache :

  <cache:annotation-driven />

    <beans:bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <beans:property name="caches">
            <beans:set>
                <beans:bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                        p:name="person"/>
           </beans:set>
        </beans:property>
    </beans:bean>

when I call this method, even if logged in or not, I am getting null back. Any help would be nice. Thanks.

In the below code line:-

@Cacheable(value = "person", condition = "#person == null")

Try to use unless in place of condition

Actually you have put up an condition that "Caching will only work if the person is null", which should be like "Caching will work unless person is null". Happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM