2012-07-09 25 views
1

如何使以下工作: - 一個Spring應用程序緩存@Cacheable註釋 - 另一個爲緩存創建鍵的spring bean(KeyCreatorBean )。使用Spring bean作爲@Cacheable註釋的關鍵

所以代碼看起來像這樣。

@Inject 
private KeyCreatorBean keyCreatorBean; 

@Cacheable(value = "cacheName", key = "{@keyCreatorBean.createKey, #p0}") 
@Override 
public List<Examples> getExamples(ExampleId exampleId) { 
    ... 

但是上面的代碼不起作用:它提供了以下異常:

Caused by: org.springframework.expression.spel.SpelEvaluationException: 
    EL1057E:(pos 2): No bean resolver registered in the context to resolve access to bean 'keyCreatorBean' 
+0

嘗試像'#{keyCreatorBean.method}',而不是'@keyCreatorBean.method'.Just隨機猜測。 – xyz 2012-07-09 16:21:54

+0

有點相關的問題:http://stackoverflow.com/questions/5749730/bean-creation-using-spel-hibernate – 2012-07-10 06:44:48

+0

你可以試試這個:http://stackoverflow.com/a/8142249/799562''但需要實現'org.springframework.cache.interceptor.KeyGenerator'。 – micfra 2012-07-10 11:13:53

回答

0

在你有一個靜態類的功能的情況下,它會像這樣

@Cacheable(value = "cacheName", key = "T(pkg.beans.KeyCreatorBean).createKey(#p0)") 
@Override 
public List<Examples> getExamples(ExampleId exampleId) { 
    ... 
} 

package pkg.beans; 

import org.springframework.stereotype.Repository; 

public class KeyCreatorBean { 

    public static Object createKey(Object o) { 
     return Integer.valueOf((o != null) ? o.hashCode() : 53); 
    } 

} 
+0

我需要使用spring bean,而不是靜態工廠方法。 – 2012-07-10 06:41:19

+0

使用'@ keyCreatorBean.createKey(#p0)'失敗,因爲它在你的情況下。也許上下文不知道緩存註解處理時的bean實例?一些春天的大師在附近? – micfra 2012-07-10 08:56:17

2

我chec注意底層緩存分辨率的實現,似乎並不是一個簡單的方法來注入一個BeanResolver,這是解決bean和評估表達式如@beanname.method所需的。

所以我也會推薦一個有點古怪的方式,沿着@micfra推薦的方式。

除了他所說的話,必須沿着這些線KeyCreatorBean,但是在內部它委託給您在申請註冊的keycreatorBean:

package pkg.beans; 

import org.springframework.stereotype.Repository; 

public class KeyCreatorBean implements ApplicationContextAware{ 
    private static ApplicationContext aCtx; 
    public void setApplicationContext(ApplicationContext aCtx){ 
     KeyCreatorBean.aCtx = aCtx; 
    } 


    public static Object createKey(Object target, Method method, Object... params) { 
     //store the bean somewhere..showing it like this purely to demonstrate.. 
     return aCtx.getBean("keyCreatorBean").createKey(target, method, params); 
    } 

} 
相關問題