You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.
It searches for the public static void main() method to flag as a runnable class.
It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
Build with Maven
First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Maven is included here. If you’re not familiar with Maven, refer to Building Java Projects with Maven.
Create the directory structure
In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:
It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.
It searches for the public static void main() method to flag as a runnable class.
It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
You could have used Spring Data to provide an implementation of your repository over a wide range of SQL or NoSQL stores, but for the purpose of this guide, you will simply use a naive implementation that simulates some latency (network service, slow delay, etc).
simulateSlowService is deliberately inserting a three second delay into each getByIsbn call. This is an example that later on, you’ll speed up with caching.
Using the repository
Next, wire up the repository and use it to access some books.
@SpringBootApplication is a convenience annotation that adds all of the following:
@Configuration tags the class as a source of bean definitions for the application context.
@EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
@ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.
There is also a CommandLineRunner that injects the BookRepository and calls it several times with different arguments.
The @EnableCaching annotation triggers a post processor that inspects every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly.
The annotations that are managed by this post processor are Cacheable, CachePut and CacheEvict. You can refer to the javadocs and the documentation for more details.
Spring Boot automatically configures a suitable CacheManager to serve as a provider for the relevant cache. See the Spring Boot documentation for more details.
Our sample does not use a specific caching library so our cache store is the simple fallback that uses ConcurrentHashMap. The caching abstraction supports a wide range of cache library and is fully compliant with JSR-107 (JCache).
Build an executable JAR
You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you are using Gradle, you can run the application using ./gradlew bootRun. Or you can build the JAR file using ./gradlew build. Then you can run the JAR file:
java -jar build/libs/gs-caching-0.1.0.jar
If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package. Then you can run the JAR file:
Now that caching is enabled, you can execute it again and see the difference by adding additional calls with or without the same isbn. It should make a huge difference.
Caching Data with Spring
This guide walks you through the process of enabling caching on a Spring managed bean.
What you’ll build
You’ll build an application that enables caching on a simple book repository.
What you’ll need
How to complete this guide
Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
To start from scratch, move on to Build with Gradle.
To skip the basics, do the following:
git clone https://github.com/spring-guides/gs-caching.git
gs-caching/initial
When you’re finished, you can check your results against the code in
gs-caching/complete
.Build with Gradle
First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Gradle and Maven is included here. If you’re not familiar with either, refer to Building Java Projects with Gradle or Building Java Projects with Maven.
Create the directory structure
In a project directory of your choosing, create the following subdirectory structure; for example, with
mkdir -p src/main/java/hello
on *nix systems:Create a Gradle build file
Below is the initial Gradle build file.
build.gradle
The Spring Boot gradle plugin provides many convenient features:
public static void main()
method to flag as a runnable class.Build with Maven
First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Maven is included here. If you’re not familiar with Maven, refer to Building Java Projects with Maven.
Create the directory structure
In a project directory of your choosing, create the following subdirectory structure; for example, with
mkdir -p src/main/java/hello
on *nix systems:pom.xml
The Spring Boot Maven plugin provides many convenient features:
public static void main()
method to flag as a runnable class.Build with your IDE
Create a book repository
First, let’s create a very simple model for your book
src/main/java/hello/Book.java
And a repository for that model:
src/main/java/hello/BookRepository.java
You could have used Spring Data to provide an implementation of your repository over a wide range of SQL or NoSQL stores, but for the purpose of this guide, you will simply use a naive implementation that simulates some latency (network service, slow delay, etc).
src/main/java/hello/SimpleBookRepository.java
simulateSlowService
is deliberately inserting a three second delay into eachgetByIsbn
call. This is an example that later on, you’ll speed up with caching.Using the repository
Next, wire up the repository and use it to access some books.
src/main/java/hello/Application.java
@SpringBootApplication
is a convenience annotation that adds all of the following:@Configuration
tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.@EnableWebMvc
for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up aDispatcherServlet
.@ComponentScan
tells Spring to look for other components, configurations, and services in thehello
package, allowing it to find the controllers.The
main()
method uses Spring Boot’sSpringApplication.run()
method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.There is also a
CommandLineRunner
that injects theBookRepository
and calls it several times with different arguments.src/main/java/hello/AppRunner.java
If you try to run the application at this point, you’ll notice it’s quite slow even though you are retrieving the exact same book several times.
As can be seen by the timestamps, each book took about three seconds to retrieve, even though it’s the same title being repeatedly fetched.
Enable caching
Let’s enable caching on your
SimpleBookRepository
so that the books are cached within thebooks
cache.src/main/java/hello/SimpleBookRepository.java
You now need to enable the processing of the caching annotations
src/main/java/hello/Application.java
The
@EnableCaching
annotation triggers a post processor that inspects every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly.The annotations that are managed by this post processor are
Cacheable
,CachePut
andCacheEvict
. You can refer to the javadocs and the documentation for more details.Spring Boot automatically configures a suitable
CacheManager
to serve as a provider for the relevant cache. See the Spring Boot documentation for more details.Our sample does not use a specific caching library so our cache store is the simple fallback that uses
ConcurrentHashMap
. The caching abstraction supports a wide range of cache library and is fully compliant with JSR-107 (JCache).Build an executable JAR
You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you are using Gradle, you can run the application using
./gradlew bootRun
. Or you can build the JAR file using./gradlew build
. Then you can run the JAR file:If you are using Maven, you can run the application using
./mvnw spring-boot:run
. Or you can build the JAR file with./mvnw clean package
. Then you can run the JAR file:Test the application
Now that caching is enabled, you can execute it again and see the difference by adding additional calls with or without the same isbn. It should make a huge difference.
This excerpt from the console shows that the first time to fetch each title took three seconds, but each subsequent call was near instantaneous.
Summary
Congratulations! You’ve just enabled caching on a Spring managed bean.
The text was updated successfully, but these errors were encountered: