一、准备阶段
安装,启动,配置nacos 传送门
二、添加配置
1、pom依赖
<!-- nacos --> <dependency> <groupId>com.alibaba.nacos</groupId> <artifactId>nacos-spring-context</artifactId> <version>1.1.1</version> </dependency>
2、配置文件
spring项目使用nacos有两种配置方法,分别是注解方式和xml方式。
注解方式是在类上面加获取nacos配置信息的相关注解。需要用的时候自行百度。据说是这种方便。实际项目中没有应用成功。
xml方式。
1.先新建一个nacos.xml文件。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:nacos="http://nacos.io/schema/nacos" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://nacos.io/schema/nacos http://nacos.io/schema/nacos.xsd"> <nacos:annotation-driven/> <nacos:global-properties server-addr="xxx" namespace="xxx" username="nacos" password="nacos"/> <nacos:property-source data-id="xxx" group-id="uat" auto-refreshed="true"/> </beans>
注意:如果有需要设置nacos用户名和密码(一般都需要),上面pom中添加的nacos的版本必须在0.3.6以上。0.3.6以下的版本没有username和password的配置。具体可看nacos自带的global-properties类。
2.在spring配置文件中引入nacos.xml。
<import resource="classpath:spring-conf/nacos.xml"/>
spring配置文件中可能会有一些数据库相关配置,redis相关配置的引用,打包之后去target下检查一下是否引用成功。
3.使用注解获取nacos相关配置。
@NacosValue(value = "${test}",autoRefreshed = true) private String test;
注意:此处注解中的autoRefreshed 和nacos.xml中的auto-refreshed都需要加上才能实现自动刷新。