配置自動更新
Nacos的配置文件變更后,微服務無需重啟就可以感知,不過需要通過下面兩種配置方式實現:
1.方式一:在@Value注入的變量所在類上添加注解@RefreshScope
@Slf4j @RestController @RequestMapping("/user") @RefreshScope public class UserController { @Autowired private UserService userService; @Value("${pattern.dateformat}") //Value注解 可以讀取配置 private String dateformat;
2.方式二:使用@ConfigurationProperties注解(可以新建一個類專門用來完成配置加載)
@Data @Component @ConfigurationProperties(prefix = "pattern") public class PatternProperties { private String dateFormat; }
public class UserController { @Autowired private UserService userService; @Autowired private PatternProperties patternProperties; // @Value("${pattern.dateformat}") //Value注解 可以讀取配置 // private String dateformat; @GetMapping("now") public String now(){ return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateFormat())); }