Spring Boot 3整合Nacos,配置namespace
今天给Spring Boot3
项目整合了Nacos
,记录一下步骤,主要是参考官网Nacos 融合 Spring Boot3,成为注册配置中心。两者就差一个namespace
配置,官网没有提到这个,application.yml
里面输入这个配置也没有提示。
步骤如下:
nacos中创建一个配置,data_id
为:zxxxx-ai.yml
,默认组
pom文件引入maven依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-alibaba-nacos-config</artifactId><version>2023.0.3.2</version></dependency>
application配置文件添加配置项
spring:application:name: zxxxx-ainacos:# 账号和密码可以配置在nacos下,也可以在config下username: 账号config:password: 密码server-addr: xxx.xxx.xxx.xxx:8848# 命名空间配置在这namespace: 命名空间IDconfig:import:# 可以加上optional:前缀。如果Group不是DEFAULT_GROUP需加上?group=GROUP_NAME后缀- nacos:zxxxx-ai.yml
使用
import com.alibaba.cloud.nacos.annotation.NacosConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class ConfigController {@Value("${plainKey}")String testKey;// 需要指定dataId和group@NacosConfig(dataId = "zxxxx-ai.yml", group = "DEFAULT_GROUP", key = "rate")String rate;@RequestMapping("/testPlainKey")public String test() {return testKey;}@RequestMapping("/rate")public String rate() {return rate;}}