Spring Cache @Cacheable - not working while calling from another method of the same bean

后端 未结 9 1468
执念已碎
执念已碎 2020-11-27 10:06

Spring cache is not working when calling cached method from another method of the same bean.

Here is an example to explain my problem in clear way.<

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 11:03

    The example below is what I use to hit the proxy from within the same bean, it is similar to @mario-eis' solution, but I find it a bit more readable (maybe it's not:-). Anyway, I like to keep the @Cacheable annotations at the service level:

    @Service
    @Transactional(readOnly=true)
    public class SettingServiceImpl implements SettingService {
    
    @Inject
    private SettingRepository settingRepository;
    
    @Inject
    private ApplicationContext applicationContext;
    
    @Override
    @Cacheable("settingsCache")
    public String findValue(String name) {
        Setting setting = settingRepository.findOne(name);
        if(setting == null){
            return null;
        }
        return setting.getValue();
    }
    
    @Override
    public Boolean findBoolean(String name) {
        String value = getSpringProxy().findValue(name);
        if (value == null) {
            return null;
        }
        return Boolean.valueOf(value);
    }
    
    /**
     * Use proxy to hit cache 
     */
    private SettingService getSpringProxy() {
        return applicationContext.getBean(SettingService.class);
    }
    ...
    

    See also Starting new transaction in Spring bean

提交回复
热议问题