1

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.

4

1 回答 1

2

在下面的代码行中: -

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

尝试使用unless代替condition

实际上,您提出了一个条件,即“缓存仅在人员为空时才起作用”,这应该类似于“缓存将起作用,除非人员为空”。快乐编码。

于 2015-08-06T09:12:16.930 回答