Spring 配置文件热重载

目录

手动

自动

方式3


手动

/**
 * 重新加载配置文件
 */
@RequestMapping(value="refresh")
public void refresh(HttpServletRequest request){
    XmlWebApplicationContext context =
            (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
    context.refresh();
}

自动

pom.xml

<!--监控+refresh配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

application.properties 

server.port=8080
local.test=helloworld
#management.security.enabled=false
management.endpoints.web.exposure.include=*

TestController

package com.xiaoyu.autorefresh.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;

@RestController
@RefreshScope
public class TestController {
    private static int port;

    @Value("${server.port}")
    public void setPort(int port){
        this.port = port;
    }

    @GetMapping("/test/port")
    public int port(){
        return port;
    }
}

方式3

一、原理说明

    实现依赖spring cloud的ContextRefresher对象和文件监听器

二、实现思路

  1、使用apache的commons-io的文件监听器来监控配置文件是否变动,当配置文件变动后调用contextRefresher.refresh()方法使Spring重新加载配置信息

    2、在需要支持配置变化的使用类添加@RefreshScope注解用来表示该类下的@Value需要更新配置信息

    3、spring boot的scheduled会因为refresh()方法而失效,所以需要调度类继承ApplicationListener接口并在刷新事件变更后调用一次调度方法即可

三、实现方法

    1、添加commons-io依赖

    2、编写一个文件监听启动类继承CommandLineRunner接口在run()方法中启动文件监听器

       FileAlterationMonitor monitor = new FileAlterationMonitor(1000);

       FileAlterationObserver observer = new FileAlterationObserver(file);

        observer.addListener(new ConfigFileListener());

        monitor .addObserver(observer);

        monitor.start();

    3、编写一个ConfigFileListener类继承FileAlterationListenerAdaptor,在onFileChange()方法中调用

contextRefresher.refresh()即可

    4、优化代码发所有的配置类尽量走配置类,在配置类添加@RefreshScope注解

    5、在调度类添加ApplicationListener接口在onApplicationEvent()实现方法中调用一次调度类

        this.myScheduled();

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值