当您尝试使用 Spring Boot 缓存功能时@Cacheable
,
你不需要启动模块spring-boot-starter-cache
这在 Spring Initializr 中被称为“Spring Cache Abstraction”。
// very basic gradle project setup on spring initializr, with zero dependencies
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
public record Student(String name, int age) {
}
@Repository
public class StudentRepo {
@Cacheable("cache")
public Student get() {
System.out.println("No cache");
return new Student("Fred", 18);
}
}
// in any spring component
@EventListener(ApplicationReadyEvent.class)
public void init() {
System.out.println(repo.get());
System.out.println(repo.get());
System.out.println(repo.get());
System.out.println(repo.get());
System.out.println(repo.get());
}
这就是结果。
No cache
Student[name=Fred, age=18]
Student[name=Fred, age=18]
Student[name=Fred, age=18]
Student[name=Fred, age=18]
Student[name=Fred, age=18]
显然缓存起作用了。根据文档,它可能是并发哈希图。
我明白了这是怎么可能的。根据maven存储库中的依赖关系,spring-boot-starter-cache
给你:
org.springframework » spring-context-support
org.springframework.boot » spring-boot-starter
我们已经有spring-boot-starter
,所以深入研究spring-context-support
,
org.springframework » spring-beans
org.springframework » spring-context
org.springframework » spring-core
嗯,他们看起来很熟悉。因为这些正是spring-boot-starter
已经有了。
基本上,入门模块是传递依赖项。但即便如此,我还是看不出什么spring-boot-starter-cache
正是用于激活缓存功能,因为它仅适用于spring-boot-starter
anyway.
现在我想知道的是:为什么我应该添加spring-boot-starter-cache
?