我们在项目中使用 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
}
}
进入方法时没有缓存拦截器。到目前为止我们检查的内容:
- 我们不从类内部调用此方法,而是从外部调用。所以问题不在于导致绕过代理的内部调用。
- 我们已经为这个类添加了一个接口(interface),我们改变了调用这个类的注入(inject)以使用接口(interface)表示而不是具体类。
我们以这种方式在我们的应用上下文中定义了缓存管理器:
<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* 存在并且是空的。
任何关于为什么这不起作用的想法将不胜感激。谢谢!
更新(来自以下评论的汇总):
==========================================**
这是一个遗留代码,可以很好地处理我提供的类和定义。我在这里谈论的方法是新的,但类(class)的其余部分在过去确实有效。所以我们正在努力了解发生了什么变化。我们也已经尝试将注释替换为 spring Cacheable,但仍然没有:/ 也许这取决于调用这个新方法的代码,它来自与我们用于其他方法的不同的 spring bean。但我仍然找不到问题。
还尝试按照下面的答案返回 boolean 值而不是 boolean 值,但没有成功。 我们有一个新线索可能与我们注入(inject) bean 的方式有关(使用@Autowire)。如果确实如此,将会更新。
最佳答案
这个问题可能与 Springs 加载 bean 的顺序有关。尝试从 Authenticator 声明中删除 @Autowire 注释,然后手动进行 Autowiring 。像这样的东西:
/**
* 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;
}
}
关于java - @Cachable 注解不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924873/