【问题标题】:What's the difference between @Cacheable Method and @Cacheable Class on ehcacheehcache 上的@Cacheable 方法和@Cacheable 类有什么区别
【发布时间】:2014-07-10 06:53:33
【问题描述】:

使用 ehcache 我注意到@Cacheable 注解可以用在类声明之上或方法声明之上,例如;

可缓存类:

@Cacheable
class CacheableClass{
    Long l;
    Integer i;
    String s;


}

可缓存方法:

    class ...
            @Cacheable
            public List<ToBeCached> getCacheableClassList()
            {
                    ...
            }

如果@Cacheable 在一个类的顶部,那么你不能给出缓存的名字,但是如果你在一个方法之上声明,你可以给出配置xml中声明的缓存的名字。我想我错过了一些东西,因为使用 @Cacheable 进行类声明对我来说似乎已经过时了。

【问题讨论】:

  • 你使用哪个@Cacheable - javax、spring cache 或任何其他第三方缓存?
  • 是的,对于 @Cacheable 类来自休眠的事实,你是对的......这令人讨厌。那么呢?还是有什么区别?

标签: java spring hibernate ehcache


【解决方案1】:

使用 ehcache-spring-annotations :

@com.googlecode.ehcache.annotations.Cacheable(cacheName = "test") 如果我们在 type level 给出这个,那么它会给出错误提示 The此位置不允许使用注释 @Cacheable

根据我读过的文档 Annotation Placement :

  1. 关于方法。
  2. 在界面上或
  3. 在类的公共方法上

Spring 建议您只使用 @Cacheable 注解来注解具体类的方法,而不是注解接口的方法。

使用代理时,您应该只将@Cacheable 注解应用于具有公共可见性的方法。如果您使用 @Cacheable 批注对受保护的、私有的或包可见的方法进行批注,则不会引发错误,但被批注的方法不会显示配置的可缓存设置。

使用 Spring Cache

如果你使用 @org.springframework.cache.annotation.Cacheable(value="test") 其中 value 代表缓存的名称。您可以在类型和/或方法级别指定。

你可以试试这个并告诉你是否出错:-

@com.googlecode.ehcache.annotations.Cacheable(cacheName = "test")
@org.springframework.cache.annotation.Cacheable(value="")
public class PortalDatabaseAdapterImpl{

    @com.googlecode.ehcache.annotations.Cacheable(cacheName="test")
    @org.springframework.cache.annotation.Cacheable(value="test")
    public List<PageControl> getLoginPage() {}
}

如果你没有收到错误,那么我必须更新自己。

【讨论】:

    【解决方案2】:

    在方法级别使用@Cacheable 意味着,方法的结果被缓存。 在接口级别使用@Cacheable 用于定义自定义注释,如下所示,

    //自定义注解

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    @Cacheable(value="books", key="#isbn")
    public @interface SlowService {
    }
    

    以下代码

    @Cacheable(value="books", key="#isbn")
    public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
    

    可以替换为

    @SlowService
    public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
    

    但我从未见过在 Class 级别应用 @Cacheable 注解。

    【讨论】:

    • 我不清楚上面的代码(findBook 方法)做了什么。它是否也从缓存中获取?假设这本书被预先缓存并调用了 findBook 方法,它应该返回这本书。它是否直接返回书而不是运行该方法?还是只是缓存返回值?
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2019-01-30
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2012-03-31
    • 2019-10-12
    相关资源
    最近更新 更多