文章目录
1 配置
Spring项目中对Nacos的配置:
spring:
profiles:
active: ${profiles.active:dev}
application:
name: 应用名称
cloud:
nacos:
config:
enabled: true
file-extension: yml
group: nacos上的group
debug: false
---
spring:
profiles: dev
cloud:
nacos:
config:
username: nacos
password: nacos
server-addr: nacos所在的地址+端口
namespace: nacos的命名空间
本次测试时,在对应的Nacos上,所在组创建配置文件,在其中增加:
bill:
base:
url:
test: https://cms.wangdian.cn/
代码
1 pom依赖
在原先springboot的依赖的基础上,增加:
<!-- Nacos读取配置-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2 配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
/**
* 接口地址:在nacos中配置之后,在此处增加
*
* @version V1.0
* @author: fengjinsong
* @date: 2022年03月01日 09时38分
*/
@Data
@ConfigurationProperties(prefix = HttpUrlProperties.PREFIX)
@RefreshScope
public class HttpUrlProperties {
/**
* URL 配置的前缀
*/
public static final String PREFIX = "bill.base.url";
/**
* 测试
*/
private String test;
}
2 启动类上
增加
@EnableConfigurationProperties(value = {HttpUrlProperties.class})
3 使用时
直接使用 Spring注入即可。
@Resource
private HttpUrlProperties httpUrlProperties;