原文网址:SpringBoot--手写组件动态更新@Value的值_IT利刃出鞘的博客-CSDN博客
本文手写组件,动态更新SpringBoot里@Value的值(无需重启服务)。
不是可以用@RefreshScope吗?为什么要手写组件?
动态更新配置属性其实有四种方式:
这四种方式的对比:
| 比较项 | @RefreshScope | 用类表示配置 | ApplicationContext | 本文组件 |
| 启动时检查空值 | 是 (没配置会报错,能及时发现问题) | 否 (没配置不报错,无法及时发现问题) | 否 | 是 |
| 是否有失效的情况 | 是 详见: 这里。 | 否 | 否 | 否 |
| 易用性 | ☆☆☆☆☆ | ☆☆☆ | ☆☆ | ☆☆☆☆☆ |
从上边可以发现,本文组件是最完美的!
Controller代码
- package com.knife.example.business.product.controller;
-
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @Api(tags = "商品")
- @RestController
- @RequestMapping("product")
- public class ProductController {
- @Value("${key1:aa}")
- private String key1;
-
- @ApiOperation("测试")
- @GetMapping("detail")
- public String detail() {
- return key1;
- }
- }
测试
访问:http://localhost:8080/doc.html
修改Nacos,将key1改为bb,不重启应用。
再次请求:(可见,已经自动更新啦)
上边是文章的部分内容,为便于维护,全文已转移到此地址:手写组件动态更新@Value的值 - 自学精灵