Spring Framework (24 Part Series)
1 Spring Configuration
2 External Properties in Spring
… 20 more parts…
3 Profiles in Spring
4 Spring Expression Language (SpEL)
5 How Spring implements Singleton Beans
6 Converting explicit into implicit configuration in Spring
7 Autowiring in Spring
8 Lazy Beans in Spring
9 @PostConstruct and @PreDestroy in Spring
10 Stereotype and Meta Annotations in Spring
11 Spring’s FactoryBean Interface
12 The Spring Bean Lifecycle
13 Spring AOP
14 Caching in Spring
15 Spring JDBC
16 Spring Transaction Management
17 JPA with Spring
18 JPA with Spring Boot
19 Spring Web MVC
20 Spring Boot for war
21 Spring MVC REST
22 Reactive Spring Applications
23 Spring Security
24 Spring Injection Types
When you have a method that always returns the same result for the same arguments (calculations, queries, requests, etc.), you can implement caching. You just need to mark the method as cacheable:
@Cacheable("books")
public Book findBook(String refId) {...}
Enter fullscreen mode Exit fullscreen mode
Its result is stored in a cache and the subsequent invocations (with the same arguments) will fetch the data from the cache using the key, and the method will not be executed.
The @Cacheable annotation has two main attributes, the value (name of the cache) and the key (for each cached data-item). In the previous example, we used a default key. Let’s see an example with a custom key, where we can use SpEL (see Spring Expression Language) and arguments of method:
@Cacheable(value="books", key="#refId.toUpperCase()")
public Book findBook(String refId) {...}
// Only cache if condition is true
@Cacheable(value="books", key="#title", condition="#title.length < 10")
public Book findBook(String title, boolean checkWarehouse) {...}
// Using an object property
@Cacheable(value="books", key="#isbn.rawNumber")
public Book findBook(ISBN isbn, boolean checkWarehouse) {...}
Enter fullscreen mode Exit fullscreen mode
Caching must be enabled using the @EnableCaching annotation in the configuration class (see Spring Configuration)
Spring Framework (24 Part Series)
1 Spring Configuration
2 External Properties in Spring
… 20 more parts…
3 Profiles in Spring
4 Spring Expression Language (SpEL)
5 How Spring implements Singleton Beans
6 Converting explicit into implicit configuration in Spring
7 Autowiring in Spring
8 Lazy Beans in Spring
9 @PostConstruct and @PreDestroy in Spring
10 Stereotype and Meta Annotations in Spring
11 Spring’s FactoryBean Interface
12 The Spring Bean Lifecycle
13 Spring AOP
14 Caching in Spring
15 Spring JDBC
16 Spring Transaction Management
17 JPA with Spring
18 JPA with Spring Boot
19 Spring Web MVC
20 Spring Boot for war
21 Spring MVC REST
22 Reactive Spring Applications
23 Spring Security
24 Spring Injection Types
原文链接:Caching in Spring
暂无评论内容