[英]@Cachable annotation does not work
我們在項目中使用ehcache進行緩存。
import com.googlecode.ehcache.annotations.Cacheable;
// Other imports
@Component
public class Authenticator{
@Cacheable(cacheName = "rest_client_authorized")
public boolean isUserAuthorized(final String user, final String sessionId) {
// Method code
}
}
進入方法時,沒有緩存攔截器。 到目前為止我們檢查的東西:
我們以這種方式在應用程序上下文中定義了緩存管理器:
<ehcache:annotation-driven cache-manager="ehCacheManager" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<!-- use a share singleton CacheManager -->
<property name="shared" value="true" />
</bean>
緩存定義如下:
<cache name="rest_client_authorized"
eternal="false"
maxElementsInMemory="50"
overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU" />
當我們使用Jconsole測試緩存管理器時,我們可以看到緩存* rest_auth_disabled *存在且為空。
關於為什么這不起作用的任何想法將非常感激。 謝謝!
更新(來自以下評論的匯總) :
========================================== **
這是一個遺留代碼,與我提供的類和定義一起工作得很好。 我在這里談論的方法是新的,但課程的其余部分確實在過去工作。 所以我們正在努力去理解發生了什么變化。 我們還嘗試將注釋替換為spring Cacheable,但仍然沒有:/可能這取決於調用此新方法的代碼,該方法來自與我們用於其他方法的Spring bean不同的Spring bean。 但我仍然找不到問題。
還嘗試在下面的答案后返回布爾而不是布爾值,但它不起作用。 我們有一個新的領導,這可能與我們注入bean的方式有關(使用@Autowire)。 如果確實如此,將會更新。
此問題可能與Spring加載bean的順序有關。 嘗試從Authenticator聲明中刪除@Autowire注釋,並手動執行自動裝配。 就像是:
/**
* Class that uses Authenticator
*/
public class X {
// Don't use @autowire here
public Authenticator athenticator;
public void doSomething() {
manuallyAutowire();
}
public void manuallyAutowire() {
if(authenticator == null) {
authenticator = ApplicationContextUtils.getApplicationContext().
getBean(authenticator.class);
}
}
哪里
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(final ApplicationContext appContext)
throws BeansException {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
}
@Cacheable中參數cacheName的值應與應用程序上下文中<cache>聲明的name屬性值相同
我認為你在這里混合了一些東西 - 你已經使用過com.googlecode.ehcache.annotations.Cacheable
,如果你想要Spring緩存支持,它實際上應該是org.springframework.cache.annotation.Cacheable
。 那么緩存攔截器應該干凈利落。
據我所知,Spring Ehcache注釋建議兩個參數作為返回對象應該有一個原始類型缺乏的equals()
和hashCode()
方法。
我不確定這個框架是否正在將原語轉換為它們的包裝變體(例如Integer
或Boolean
)。 嘗試返回包裝器變量Boolean
而不是基本類型,看它是否有效。
我不確定的另一件事是它如何(以及如果)處理final
參數。 如果我的第一個想法不起作用,請嘗試刪除final
關鍵字,如果可能,看看它是否有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.