Spring 3.1 @Cacheable - method still executed

后端 未结 3 811
盖世英雄少女心
盖世英雄少女心 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 findPersons(int[] ids) {
            List list = new ArrayList();
            for (int id : ids) {
                list.add(_personDao.findPerson(id));
            }
            return list;
        }
    }
    

提交回复
热议问题