V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ArthurKing
V2EX  ›  程序员

帮看下这种多态情况下如何使用 Spring Cache?

  •  
  •   ArthurKing · 2020-03-16 17:40:11 +08:00 · 1072 次点击
    这是一个创建于 1513 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Person{
    	String id;
    	String name;
    }
    
    interface A {
      String getOnePerson(String id);
      List<Person> getPersonList();
    } 
    
    abstract class B implements A{
       abstract List<Person> getPersonList();
       String getOnePerson(String id){
           List<Person> list = this.getList();
           for (Person p : dishList) {
                  if (p.getId().equals(id)) {
                      return dish;
                  }
           }
         return null;
     }
    }
    
    class C extends B{
      @Cacheable(xxxxx)
    	List<Person> getPersonList(){
    	   return Lists.newArrayList(p1,p2,p3)
    	}
    }
    
    class D extends B{
      @Cacheable(yyyyy)
    	List<Person> getPersonList(){
    	   return Lists.newArrayList(p4,p5,p6)
    	}
    }
    
    
    
    

    这种情况下调用 A.getOne 方法时,属于是内部调用是不会走缓存的。能否在不冗余代码的情况下使用缓存?

    第 1 条附言  ·  2020-10-29 11:29:27 +08:00

    最终解决方案,使用AopContext.currentProxy()),需要在启动类上加@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)

    abstract class B implements A{
       abstract List<Person> getPersonList();
       String getOnePerson(String id){
           List<Person> list = (A)(AopContext.currentProxy())).getList();
           for (Person p : dishList) {
                  if (p.getId().equals(id)) {
                      return dish;
                  }
           }
         return null;
     }
    }
    
    2 条回复    2020-03-16 18:48:49 +08:00
    luckyrayyy
        1
    luckyrayyy  
       2020-03-16 18:18:39 +08:00
    内部调用是默认不缓存的,用 AspectJ 的方式,参考这个答案:
    https://stackoverflow.com/questions/12115996/spring-cache-cacheable-method-ignored-when-called-from-within-the-same-class
    ArthurKing
        2
    ArthurKing  
    OP
       2020-03-16 18:48:49 +08:00
    @luckyrayyy #1 这个我看过了,我疑惑的地方在于,@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)这个要加到我的抽象类上,然后抽象类中注入 A ?这样的话在注入 A 的时候就会找到多个实现。
    另外我使用 A 中方法的时候是通过在 C/D 上的注解通过工厂方法获取的具体实例,在抽象类中就没法这么搞了吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4512 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:31 · PVG 13:31 · LAX 22:31 · JFK 01:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.