NOTE

2.35 Usage

Create a project, configure pom.xml, and use Spring Boot caching with Application, TestController, and TestService.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Create a Project

2. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zsk.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.20.RELEASE</version>
    </parent>

    <dependencies>
        <!-- aop -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3. Code

  • Application.java
@EnableCaching//enabled by default
@SpringBootApplication()
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
        System.out.println("==================================Service started==================================");

    }
}
  • TestApplication.java
@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class TestApp
{
    @Autowired
    private TestController testController;

    @Test
    public void test()
    {
        testController.test();//The first call enters the TestService logic.
        testController.test();//The second call returns the cache directly from the proxy class.
    }
}
  • TestController
@Service
public class TestController
{
    @Autowired//What is injected here is actually a proxy class.
    private TestService testService;

    public void test()
    {
        String byId = testService.getById(1);
        System.out.println(byId);
    }
}
  • TestService
@Service
public class TestService
{
    @Cacheable("test")
    public String getById(Integer id)
    {
        return "" + id;
    }
}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub