假如我们有一个简单项目(nacos_multi_env2),该项目需要在开发环境(dev)和生产环境(prod)运行。
我们可以通过 Nacos 配置集 ID + spring.profiles.active 的方式来实现多环境隔离。
登录 Nacos,创建 nacos_multi_env2 命名空间,然后在该命名空间中创建 example-dev 和 example-prod 配置集,如下图:

其中,example-dev 配置集内容如下:
type=dev
example-prod 配置集内容如下:
type=prod
使用 IDEA 创建一个 Spring Boot 项目,项目结构图如下:

该项目存在三个 properties 配置文件,内容分别如下:
# 激活生产环境 spring.profiles.active=prod # 指定 Nacos 服务地址 nacos.config.server-addr=127.0.0.1:8848 # 指定 Nacos 命名空间 nacos.config.namespace=54387758-b92f-40f0-92a6-2296f8272d52
# 没有
# 没有
项目的启动类,使用 @NacosPropertySource 注解加载 dataId 为 “example + ${spring.profiles.active}” 的配置源,并开启自动更新。
如果 ${spring.profiles.active} 为 dev,则加载 example-dev 配置源。
如果 ${spring.profiles.active} 为 prod,则加载 example-prod 配置源。
代码如下:
package com.hxstrive.nacos;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
// 注意:${spring.profiles.active} 是可以被解析的
@NacosPropertySource(dataId = "example-${spring.profiles.active}", autoRefreshed = true)
public class MainApplication {
   public static void main(String[] args) {
       SpringApplication.run(MainApplication.class, args);
   }
}一个简单的控制器,通过 @NacosValue 注解注入 type 配置项,代码如下:
package com.hxstrive.nacos;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@Controller
@RequestMapping("config")
public class ConfigController {
   @NacosValue(value = "${type:}", autoRefreshed = true)
   private String type;
   @RequestMapping(value = "/get", method = GET)
   @ResponseBody
   public String get() {
       return type;
   }
}运行 MainApplication 类,启动项目,项目启动成功后,通过浏览器访问 http://localhost:8080/config/get 地址,输出如下:

如果将 spring.profiles.active 设置为 dev,则将输出 dev 字符串。
