I have enabled Caching by using @Cacheable
annotation on a method which has the following declaration:
@Cacheable(value = "myCache", key = "#t+ '_' + #key", condition = "#key != null")
public <T> T get(String t, VendorProperty<T> key, T defaultValue) {
return get(t, key).orElse(default_value);
}
However, this throws NotSerializableException
if the object it is trying to cache is not Serializable (for example: DateTimeFormatter
).
I was wondering if it is possible to cache objects only when the object is Serializable to avoid this exception.
I am using memcache
to cache the objects using simple-spring-memcache
library.
PS: I can't implement the Serializable
interface as DateTimeFormatter
is a predefined class.
The suggestion above won't work. #root.target is the target object being executed (in this case the service object). So it will appear to work because the service object is not serializable and so the object in question won't be cached but neither will anything else.
You need to leverage the "unless" condition using the result variable:
@Cacheable(value = "myCache",
key = "#t+ '_' + #key",
condition = "#key != null"
unless="!(#result instanceof T(java.io.Serializable))")