读取nacos的配置

  • Post author:
  • Post category:其他


1.开发环境

java:17

springboot:2.7.5

springcloud:2021.0.4

springcloudalibaba:2021.0.4.0

2.maven依赖

<properties>

<java.version>17</java.version>

<spring-cloud-alibaba.version>2021.0.4.0</spring-cloud-alibaba.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-configuration-processor</artifactId>

<optional>true</optional>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

<dependencyManagement>

<dependencies>

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-alibaba-dependencies</artifactId>

<version>${spring-cloud-alibaba.version}</version>

<type>pom</type>

<scope>import</scope>

</dependency>

</dependencies>

</dependencyManagement>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

<configuration>

<excludes>

<exclude>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

</exclude>

</excludes>

</configuration>

</plugin>

</plugins>

</build>

3.application.properties配置参数

server.port=9010

spring.application.name=ts-1

spring.cloud.nacos.config.group=DEFAULT_GROUP

spring.cloud.nacos.config.server-addr=10.21.10.8:8848

spring.config.import=optional:nacos:test.yml

4.编写nacos参数读取类

package com.example.kc1.config;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "configdata.user")
public class UserConfig {
    private String name;
    private Integer age;
}

5.nacos上新增test.yml配置文件,格式yaml

configdata:

user:

age: 21

name: freeman

6.启动类添加注解

@SpringBootApplication
@ConfigurationPropertiesScan("com.example.kc1.config")
public class Kc1Application {

    public static void main(String[] args) {
        SpringApplication.run(Kc1Application.class, args);
    }

}

7.使用

@RestController
@RequiredArgsConstructor
public class NacosController {
    private final UserConfig userConfig;

    @GetMapping("/user")
    public ResponseEntity getUser(){
        return ResponseEntity.ok("hi,"+userConfig.getName());
    }
}

参考文献:


Configuration Metadata



https://www.baeldung.com/configuration-properties-in-spring-boot



https://github.com/alibaba/spring-cloud-alibaba/tree/2021.x/spring-cloud-alibaba-examples/nacos-example/nacos-config-2.4.x-example



版权声明:本文为miaowansheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。