1

Is there a way using the Spring Framework's cache abstraction to always return a cached incarnation of an object?

I have an image resizing method. The resize() method returns a temporary File which is cached using my hand-rolled binary Cache using Spring's cache abstraction. The method itself is cached via @Cacheable and all works fine.

The difficulty is that I need to somehow clean up the temporary files generated by this method after they've been added to the cache.

In other words, the current behaviour is:

  1. First invocation of resize() - returns generated file at /tmp/somefile.jpg which is added to the cache by Spring.

  2. Second invocation of resize() - results in a cache hit, so returns file from /myCache/somefile.jpg

This results in temporary files lingering around.

I can't delete the source file in my Cache#put(Object key, Object value) method, as this is the file that's returned from the non-cached invocation of the associated method.

Has anyone encountered a similar situation and solved it with an elegant solution? Ideally, I'd like all invocations of the cacheable method to return the cached object.

nullPainter
  • 2,676
  • 3
  • 22
  • 42
  • I hope the only solution isn't http://stackoverflow.com/questions/10827267/how-to-prevent-a-return-value-from-cache-to-be-changed-in-spring-cacheable?rq=1, as my AspectJ is decidedly ropey...! – nullPainter Jan 25 '13 at 08:40

1 Answers1

2

I've worked around the issue by interacting directly with Cache#get() and Cache#put(), bypassing Spring's more elegant annotation-based approach.

It's not beautiful, but it works.

nullPainter
  • 2,676
  • 3
  • 22
  • 42