2

以下を機能させる方法: - @Cacheable アノテーションでキャッシュする必要があるメソッドを持つ Spring Bean - キャッシュのキーを作成する別の Spring Bean (KeyCreatorBean)。

したがって、コードは次のようになります。

@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'
4

2 に答える 2

2

基盤となるキャッシュ解決の実装を確認しましたが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);
    }

}
于 2012-07-10T11:31:02.173 に答える
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);
    }

}
于 2012-07-09T22:17:07.470 に答える