Spring 3.1 @Cacheable - method still executed

后端 未结 3 798
盖世英雄少女心
盖世英雄少女心 2021-02-01 04:10

I\'m trying to implement Spring 3.1 caching as explained here and here, but it doesn\'t seem to be working: my method is run through every time even though it is marked @cacheab

相关标签:
3条回答
  • 2021-02-01 04:37

    In addition to Lee Chee Kiam: Here is my solution for small projects with only marginal usage of bypassing (not annotated) method calls. The DAO is simply injected into itself as a proxy and calls it's own methods using that proxy instead of a simple method call. So @Cacheable is considered without doing complicated insturmentation.

    In-code documentation is strongly advidsed, as it may look strange to colleagues. But its easy to test, simple, quick to achieve and spares me the full blown AspectJ instrumentation. However, for more heavy usage I'd also advice the AspectJ solution as Lee Chee Kiam did.

    @Service
    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
    class PersonDao {
    
        private final PersonDao _personDao;
    
        @Autowired
        public PersonDao(PersonDao personDao) {
            _personDao = personDao;
        }
    
        @Cacheable(value = "defaultCache", key = "#id")
        public Person findPerson(int id) {
            return getSession().getPerson(id);
        }
    
        public List<Person> findPersons(int[] ids) {
            List<Person> list = new ArrayList<Person>();
            for (int id : ids) {
                list.add(_personDao.findPerson(id));
            }
            return list;
        }
    }
    
    0 讨论(0)
  • 2021-02-01 04:38

    From http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html

    In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with @Cacheable - considering using the aspectj mode in this case.

    and

    Method visibility and @Cacheable/@CachePut/@CacheEvict

    When using proxies, you should apply the @Cache annotations only to methods with public visibility.

    1. You self-invoke someMethod in the same target object.
    2. Your @Cacheable method is not public.
    0 讨论(0)
  • 2021-02-01 04:46

    You need to define a cache that matches the name you are referencing in you annotation ("testmethod"). Create an entry in your ehcache.xml for that cache as well.

    0 讨论(0)
提交回复
热议问题