首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不使用@PostConstruct或@AfterPropertiesSet的Spring引导缓存

不使用@PostConstruct或@AfterPropertiesSet的Spring引导缓存
EN

Stack Overflow用户
提问于 2018-11-30 08:42:20
回答 2查看 3.6K关注 0票数 3

当我的应用程序启动时,我尝试用数据初始化我的缓存,但这不起作用。我的代码:

springBootApplication

代码语言:javascript
复制
package com.r2b.springcache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan("com.r2b")
@SpringBootApplication
@EnableCaching
public class SpringCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCacheApplication.class, args);
    }

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("student");
    }
}

学生

代码语言:javascript
复制
package com.r2b.model;

public class Student {

    String id;
    String name;
    String clz;

    public Student(String id, String name, String clz) {
        super();
        this.id = id;
        this.name = name;
        this.clz = clz;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getClz() {
        return clz;
    }

    public void setClz(String clz) {
        this.clz = clz;
    }

    //Setters and getters

}

studentService

代码语言:javascript
复制
package com.r2b.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.r2b.model.Student;

@Service
public class StudentService  
{

    @Cacheable("student")
    public Student getStudentByID(String id)
    {
        try
        {
            System.out.println("Going to sleep for 5 Secs.. to simulate backend call.");
            Thread.sleep(1000*5);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        return new Student(id,"Sajal" ,"V");
    }

}

StudentController

代码语言:javascript
复制
package com.r2b.controller;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.r2b.model.Student;
import com.r2b.service.StudentService;

@RestController
public class StudentController
{

    @Autowired
    StudentService studentService;


    @PostConstruct
    public void init() {
        studentService.getStudentByID("1");
    }

    @GetMapping("/student/{id}")
    public Student findStudentById(@PathVariable String id)
    {
        System.out.println("Searching by ID  : " + id);

        return studentService.getStudentByID(id);
    }
}

pom.xml

代码语言:javascript
复制
<?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.r2b</groupId>
    <artifactId>spring-cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-cache</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

当我第一次进入http://localhost:8080/student/1时,缓存是不活动的,响应需要超过5秒,但是当我刷新时,缓存会响应,请求需要几毫秒!尽管我在postConstruct中调用了缓存方法,但我尝试使用@AfterPropertiesSet,但它也不起作用!

知道吗?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-02 12:14:20

答案很简单,但我花了几乎一天的时间,才找到了在@PostConstruct中使用@Cacheable修饰的方法。

简单地将@PostConstruct替换为@EventListener(ApplicationReadyEvent.class)

代码语言:javascript
复制
@EventListener(ApplicationReadyEvent.class)
public void init() {
    studentService.getStudentByID("1");
}

如果从使用https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/event/EventListener.html(ApplicationReadyEvent.class) 事件修饰的方法引发异常,则应用程序将退出.

票数 15
EN

Stack Overflow用户

发布于 2018-11-30 09:10:32

这不起作用,因为代理还没有初始化。这实际上是在用户指南中有记录

在代理模式(默认)中,只截获通过代理传入的外部方法调用。这意味着,即使被调用的方法标记为@Cacheable,自调用(实际上,在目标对象中调用另一个对象的方法)不会导致运行时的实际缓存。考虑在本例中使用aspectj模式。此外,代理必须完全初始化以提供预期的行为,因此您不应该在初始化代码(即@PostConstruct)中依赖此特性。

这正是你在这里要做的。缓存应该尽可能透明,所以在启动时预加载缓存对我来说有点奇怪(并且增加了启动时间)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53554045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档