Home > other >  How to get non cached result from a cacheable method?
How to get non cached result from a cacheable method?

Time:03-26

Let's say a business method annotated with @Cacheable.

@Component
class Some {

    @Cacheable
    public Some getSome() {
    }
}

Now can any caller conditionally request non cached result, as if the method is not annotated with @Cacheable at all, without evicting the cache nor using a separated method?


    void doOther() {
        // How can I get non-cached live result from some#getSome()
    }

    @Autowired
    private Some some;

I found condition and unless, but those are not for my requirements.

CodePudding user response:

Caching mechanism through @Cacheable is achieved by using proxies. To ignore caching you should unwrap proxy into real target object, and directly invoke its unwrapped method:

import org.springframework.aop.framework.AopProxyUtils;

...

@Autowired
private Some some;

void doOther() {
    Some unproxied = (Some) AopProxyUtils.getSingletonTarget(some);
    Some noncached = unproxied.getSome();
    ...
}
  • Related