NOTE

2.35 使用

1. 创建项目 2. pom.xml 3. 代码 - Application.java - TestApplication.java - TestController - TestService

Java创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 创建项目

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. 代码

  • Application.java
@EnableCaching//默认已经开启
@SpringBootApplication()
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
        System.out.println("==================================服务已启动==================================");

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

    @Test
    public void test()
    {
        testController.test();//第一次会进入TestService的逻辑
        testController.test();//第二次直接由代理类返回缓存
    }
}
  • TestController
@Service
public class TestController
{
    @Autowired//注入的这个其实是个代理类
    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;
    }
}