[Spring Boot]如何动态刷新配置

3 篇文章 0 订阅
3 篇文章 0 订阅

由于时间关系,仅记录要点:
1.引入 spring-boot-starter-actuator及spring-cloud-starter-config
2.对需要刷新的属性使用@Value注解,同时将类使用@RefreshScope注解进行标记

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@RefreshScope
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class);
    }

    @Value("${server.port}")
    private int port;

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

3.application.properties配置。(注意2.0.3版本后暴露/refresh接入点的方式与旧版本不同,需要手动设置暴露点。)

server.port=8888
management.endpoints.web.exposure.include=refresh

4.测试
4.1 启动项目,访问 http://localhost:8888/port
此时浏览器应显示8888
4.2 application.properties将server.port改为9999
4.3 http://localhost:8888/actuator/refresh
4.4 http://localhost:8888/port
此时浏览器应显示9999
(注意,即使刷新配置,tomcat并未重启,只是server.port对应的值产生了改变,并刷新到标明了@RefreshScope注解的类。所以访问tomcat时依然用8888端口)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值