1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @SpringBootTest @RunWith(SpringRunner.class) @Slf4j public class CacheTest {
@Test public void cacheTest() {
String cache = loadCache(); log.info(cache); log.info("====="); cache = loadCache(); log.info(cache); }
@Cacheable(cacheNames = "loadCache") public String loadCache() { log.info("调用方法"); return "hello world"; } }
|
Spring 缓存注解是基于Spring AOP切面,必须走代理才能生效,同类调用或者子类调用父类带有缓存注解的方法时属于内部调用,没有走代理,所以注解不生效。
解决方法: 将方法抽离到一个独立类中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @SpringBootTest @RunWith(SpringRunner.class) @Slf4j public class CacheTest {
@Autowired CacheClass cacheClass ;
@Test public void cacheTest() {
String cache = cacheClass.loadCache(); log.info(cache); log.info("====="); cache = cacheClass.loadCache(); log.info(cache); }
}
@Component class CacheClass{
@Cacheable(cacheNames = "loadCache") public String loadCache() { return "hello world"; } }
|