资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

如何在springboot中配置一个动态刷新功能

如何在spring boot中配置一个动态刷新功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

成都创新互联公司主要从事成都网站设计、成都做网站、外贸网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务东方,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108

1、pom:



  4.0.0

  com.liuyx
  test-config-refresh
  1.0-SNAPSHOT

  
    org.springframework.boot
    spring-boot-starter-parent
    1.5.4.RELEASE
     
  

  
    
      org.springframework.boot
      spring-boot-starter-web
    
    
      org.springframework.cloud
      spring-cloud-starter-config
    

    
    
      org.springframework.boot
      spring-boot-starter-actuator
    
  

  
    
      
        org.springframework.cloud
        spring-cloud-dependencies
        Dalston.SR1
        pom
        import
      
    
  

单独引入 spring-boot-starter-actuator或者spring-cloud-starter-config(spring cloud config的客户端) 是不会暴露/refresh端点的,两者同时引入之后才能暴露/refresh端点。

2、一般使用spring-cloud-starter-config的文章都会让你在bootstrap里加上配置中心服务端的地址,这里我们要脱离配置中心服务端使用,所以这些配置完全不需要。

3、对需要刷新的属性使用@Value注解,同时将类使用@RefreshScope注解进行标记,示例如下:

package com.liuyx.test;

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);
  }

  private static int port;

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

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

这里我的变量是一个static变量,所以只能在非static的set方法上加@Value注解,而不是变量定义行的上方。如果不是静态变量则可以直接写作:

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

4、application.properties配置

server.port=80
local.test=hello1
management.security.enabled=false

5、测试

1、启动项目,访问 http://localhost/port 显示 80

2、修改classpath(注意是classpath,即你编译后的class文件所处的目录)下的application.properties将server.port改为801

如何在spring boot中配置一个动态刷新功能

3、发送空post(注意是post)请求到 http://localhost:80/refresh

如何在spring boot中配置一个动态刷新功能

4、再次访问 http://localhost/port 显示 801 测试成功

关于如何在spring boot中配置一个动态刷新功能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


分享名称:如何在springboot中配置一个动态刷新功能
当前链接:http://cdkjz.cn/article/iiopjj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220