###問題 之前使用EhCache緩存數據的時候,保存的value都是基於Java的基礎類型數據,最近發現保存自定義類型的對象時,get()出來的Element要麼爲null,要麼當用Element的getValue()時拋出net.sf.ehcache.CacheException: Value xxx is not Serializable
異常。html
###解決方案java
java.io.Serializable
。由於EhCache在put對象時,是序列化保存的。 官方文檔對EhCache put方法的說明:putapi
void put(Element element)throws IllegalArgumentException,IllegalStateException,CacheException緩存
Put an element in the cache. Resets the access statistics on the element, which would be the case if it has previously been gotten from a cache, and is now being put back.code
Also notifies the CacheEventListener that:htm
the element was put, but only if the Element was actually put. if the element exists in the cache, that an update has occurred, even if the element would be expired if it was requested Parameters: element - An object. If Serializable it can fully participate in replication and the DiskStore.對象
Throws: IllegalStateException - if the cache is not Status.STATUS_ALIVE IllegalArgumentException - if the element is null CacheExceptionip
另外:EhCache的flush()方法是將緩存序列化到文件中, 緩存配置diskPersistent="true"時有用。若是put沒有序列化的對象後再flush(),從Cache中get()將獲得null(不支持序列化對象,無法持久化到文件中)。若是put後沒有flush(),則能夠get()到緩存的Element,可是當調用Element的getValue()取緩存對象時,會報net.sf.ehcache.CacheException: Value xxx is not Serializable
異常。ci