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

JavaSpringCachingEhcache

Java Problem Overview


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.

Configuration:

<cache:annotation-driven cache-manager="myCacheManager" />

<bean id="myCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
	<property name="cacheManager" ref="myCache" />
</bean>

<!-- Ehcache library setup -->
<bean id="myCache"
	class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true">
	<property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>

<cache name="employeeData" maxElementsInMemory="100"/>	

Cached service :

@Named("aService")
public class AService {

	@Cacheable("employeeData")
	public List<EmployeeData> getEmployeeData(Date date){
	..println("Cache is not being used");
	...
	}
	
	public List<EmployeeEnrichedData> getEmployeeEnrichedData(Date date){
		List<EmployeeData> employeeData = getEmployeeData(date);
		...
	}

}

Result :

aService.getEmployeeData(someDate);
output: Cache is not being used
aService.getEmployeeData(someDate); 
output: 
aService.getEmployeeEnrichedData(someDate); 
output: Cache is not being used

The getEmployeeData method call uses cache employeeData in the second call as expected. But when the getEmployeeData method is called within the AService class (in getEmployeeEnrichedData), Cache is not being used.

Is this how spring cache works or am i missing something ?

Java Solutions


Solution 1 - Java

I believe this is how it works. From what I remember reading, there is a proxy class generated that intercepts all requests and responds with the cached value, but 'internal' calls within the same class will not get the cached value.

From https://code.google.com/p/ehcache-spring-annotations/wiki/UsingCacheable

> 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 cache interception at runtime even if the > invoked method is marked with @Cacheable.

Solution 2 - Java

Since Spring 4.3 the problem could be solved using self-autowiring over @Resource annotation:

@Component
@CacheConfig(cacheNames = "SphereClientFactoryCache")
public class CacheableSphereClientFactoryImpl implements SphereClientFactory {

    /**
     * 1. Self-autowired reference to proxified bean of this class.
     */
    @Resource
    private SphereClientFactory self;

    @Override
    @Cacheable(sync = true)
    public SphereClient createSphereClient(@Nonnull TenantConfig tenantConfig) {
        // 2. call cached method using self-bean
        return self.createSphereClient(tenantConfig.getSphereClientConfig());
    }

    @Override
    @Cacheable(sync = true)
    public SphereClient createSphereClient(@Nonnull SphereClientConfig clientConfig) {
        return CtpClientConfigurationUtils.createSphereClient(clientConfig);
    }
}

Solution 3 - Java

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 https://stackoverflow.com/questions/3037006/starting-new-transaction-in-spring-bean/3037120#3037120

Solution 4 - Java

Here is what I do for small projects with only marginal usage of method calls within the same class. In-code documentation is strongly advidsed, as it may look strage 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 advice the AspectJ solution.

@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
class AService {

    private final AService _aService;

    @Autowired
    public AService(AService aService) {
        _aService = aService;
    }

    @Cacheable("employeeData")
    public List<EmployeeData> getEmployeeData(Date date){
        ..println("Cache is not being used");
        ...
    }

    public List<EmployeeEnrichedData> getEmployeeEnrichedData(Date date){
        List<EmployeeData> employeeData = _aService.getEmployeeData(date);
        ...
    }
}

Solution 5 - Java

If you call a cached method from same bean it will be treated as a private method and annotations will be ignored

Solution 6 - Java

In my Case I add variable :

@Autowired
private AService  aService;

So I call the getEmployeeData method by using the aService

@Named("aService")
public class AService {

@Cacheable("employeeData")
public List<EmployeeData> getEmployeeData(Date date){
..println("Cache is not being used");
...
}

public List<EmployeeEnrichedData> getEmployeeEnrichedData(Date date){
    List<EmployeeData> employeeData = aService.getEmployeeData(date);
    ...
}

}

It will use the cache in this case.

Solution 7 - Java

Yes, the caching will not happen because of the reasons that were already mentioned in the other posts. However I would solve the problem by putting that method to its own class (service in this case). With that your code will be easier to maintain/test and understand.

@Service // or @Named("aService")
public class AService {

    @Autowired //or how you inject your dependencies
    private EmployeeService employeeService;
 
    public List<EmployeeData> getEmployeeData(Date date){
          employeeService.getEmployeeData(date);
    }

    public List<EmployeeEnrichedData> getEmployeeEnrichedData(Date date){
        List<EmployeeData> employeeData = getEmployeeData(date);
        ...
    }

}
@Service // or @Named("employeeService")
public class EmployeeService {

    @Cacheable("employeeData")
    public List<EmployeeData> getEmployeeData(Date date){
        println("This will be called only once for same date");
        ...
    }

}

Solution 8 - Java

Use static weaving to create proxy around your bean. In this case even 'internal' methods would work correctly

Solution 9 - Java

I use internal inner bean (FactoryInternalCache) with real cache for this purpose:

@Component
public class CacheableClientFactoryImpl implements ClientFactory {

private final FactoryInternalCache factoryInternalCache;

@Autowired
public CacheableClientFactoryImpl(@Nonnull FactoryInternalCache factoryInternalCache) {
    this.factoryInternalCache = factoryInternalCache;
}

/**
 * Returns cached client instance from cache.
 */
@Override
public Client createClient(@Nonnull AggregatedConfig aggregateConfig) {
    return factoryInternalCache.createClient(aggregateConfig.getClientConfig());
}

/**
 * Returns cached client instance from cache.
 */
@Override
public Client createClient(@Nonnull ClientConfig clientConfig) {
    return factoryInternalCache.createClient(clientConfig);
}

/**
 * Spring caching feature works over AOP proxies, thus internal calls to cached methods don't work. That's why
 * this internal bean is created: it "proxifies" overloaded {@code #createClient(...)} methods
 * to real AOP proxified cacheable bean method {@link #createClient}.
 *
 * @see <a href="https://stackoverflow.com/questions/16899604/spring-cache-cacheable-not-working-while-calling-from-another-method-of-the-s">Spring Cache @Cacheable - not working while calling from another method of the same bean</a>
 * @see <a href="https://stackoverflow.com/questions/12115996/spring-cache-cacheable-method-ignored-when-called-from-within-the-same-class">Spring cache @Cacheable method ignored when called from within the same class</a>
 */
@EnableCaching
@CacheConfig(cacheNames = "ClientFactoryCache")
static class FactoryInternalCache {

    @Cacheable(sync = true)
    public Client createClient(@Nonnull ClientConfig clientConfig) {
        return ClientCreationUtils.createClient(clientConfig);
    }
}
}

Solution 10 - Java

I would like to share what I think is the easiest approach:

  • Autowire the controller and use to call the method it instead of using the class context this.

The updated code would look like:

@Controller
public class TestController {


    @Autowired TestController self;

    @RequestMapping("/test")
    public String testView(){
        self.expensiveMethod();
        return "test";
    }


    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("Cache is not being used");
    }

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBalaView Question on Stackoverflow
Solution 1 - JavaShawn D.View Answer on Stackoverflow
Solution 2 - JavaradistaoView Answer on Stackoverflow
Solution 3 - JavamolholmView Answer on Stackoverflow
Solution 4 - JavaMario EisView Answer on Stackoverflow
Solution 5 - JavaVijayView Answer on Stackoverflow
Solution 6 - JavaIbtissam IbtissamaView Answer on Stackoverflow
Solution 7 - JavamcvkrView Answer on Stackoverflow
Solution 8 - JavaDewfyView Answer on Stackoverflow
Solution 9 - JavaradistaoView Answer on Stackoverflow
Solution 10 - JavaCarlos López MaríView Answer on Stackoverflow