We use SpringCache a lot where I work. We have many methods that look something like that:
public class CitiesManager {
/**
* Get all cities, cached
*/
@Cachable( CACHE_REGION_CITIES )
public List<City> getCities() {
return getCitiesTransactional();
}
/**
* Gets all cities, cached
* This method is splitted from getCities(), to spare the redundant Transaction when Cities are fetched from cache.
*/
@Transactional
private List<City> getCitiesTransactional() {
return repository.getCities();
}
}
It works great. Problem is - City is a mutable object. And it happens that the caller of getCities() takes one city and changes it, which corrupts the cache.
With one such cache, our solution was to create a read-only interface, e.g:
public interface ReadonlyCity {
String getName();
int getPopulation();
}
That works great, but It's a hassle to do that for every class we cache.
What I would like to do is one of the two: 1. Tell SpringCache to wrap the objects it caches with a proxy that makes them immutable. For instance, by making every setFoo() method throw an UnSupportedOperationException. I know it's not air-tight, but it's good enough for me. 2. Make SpringCache serialise and deserialise objects it returns.
Or if you have other suggestions, I would like to hear them.