spring boot 配置文件动态刷新

说明

实现方式

1.建立一个spring boot工程,名称:boot-config,目录如下:

2.引入pom依赖

<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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
		<!--监控配置文件依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <!--监控+refresh配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
    <!-- 引入RefreshScope注解依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

3.application.yml文件

management:
  endpoints:
    web:
      exposure:
        include: refresh #暴露对外刷新接口
hello: 你好!! #用于测试配置文件更新

4.TestController示例

package com.zhouj.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zj
 * @title: TestController
 * @projectName boot-config
 * @description: TODO
 * @date 2020-08-1215:20
 */
@RestController
@RefreshScope
public class TestController {
          
   
	//获取配置文件的值
    @Value("${hello}")
    private String hello;
	//当访问 localhost:8080/hello 时,返回hello
    @GetMapping("/hello")
    public Object test(){
          
   
        return hello;
    }
}

5.测试

1.1启动项目,直接访问:localhost:8080/hello

结果: 可以看到,此时,配置文件的 hello是 你好!!

1.2找到项目编译文件夹,找到配置文件,修改hello的值:

1.3保存文件,访问配置文件刷新接口:http://localhost:8080/actuator/refresh

可以看到,此时,有返回信息,提示我们:hello被改变了。

1.4再次访问:localhost:8080/hello:

可以看到,此时打印出的hello已经被重新加载到运行内存里面去了。

经验分享 程序员 微信小程序 职场和发展