前提条件 Spring Cloud应用已改造为从Consul中读取配置,且应用启动正常

第一种方法

使用配置类,在启动类上使用@EnableConfigurationProperties注解引入,然后在需要使用的地方注入配置类即可

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author kevin
 * @date 2020/9/24
 */
@ConfigurationProperties(prefix = "test")
@Data
public class TestConfig {
    private String desc;
}
@SpringBootApplication
// 引入TestConfig配置类
@EnableConfigurationProperties({TestConfig.class})
public class DemoTestApplication {

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

}
/**
 * @author kevin
 * @date 2020/9/24
 */
@Controller
public class TestController {

    @Autowired
    TestConfig testConfig;

    @PostMapping("/test")
    @ResponseBody
    public void test(@RequestBody String msg) {
        // 打印在Consul中配置好的test.desc值
        System.out.println(testConfig.getDesc());
        System.out.println("-------------------------------------");
        System.out.println(msg);
    }
}

第二种方法

使用@RefreshScope、@Value注解,代码示例如下:

/**
 * @author kevin
 * @date 2020/9/9
 */
@RestController
@Slf4j
@RefreshScope
public class TestController {

    // test.print.log需要在Consul中配置
    @Value("${test.print.log:false}")
    private boolean isPrintLog;

    @GetMapping("/test")
    public void test() {
       if (isPrintLog) {
          log.info("打印日志");
       }
    }

}

修改Consul中配置并保存后,上述两种方式均会自动刷新配置值,控制台日志运行效果如下:

 

更多推荐