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

2020-03-16 17:40:11 +08:00
 ArthurKing
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 方法时,属于是内部调用是不会走缓存的。能否在不冗余代码的情况下使用缓存?

1088 次点击
所在节点    程序员
2 条回复
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
2020-03-16 18:48:49 +08:00
@luckyrayyy #1 这个我看过了,我疑惑的地方在于,@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)这个要加到我的抽象类上,然后抽象类中注入 A ?这样的话在注入 A 的时候就会找到多个实现。
另外我使用 A 中方法的时候是通过在 C/D 上的注解通过工厂方法获取的具体实例,在抽象类中就没法这么搞了吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/653330

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX