SpringBoot读取Nacos数组配置

avatar 2022年03月11日11:02:01 6 5888 views
博主分享免费Java教学视频,B站账号:Java刘哥

因为需要做一些配置放在Nacos上,方便需求人员或业务人员后期进行修改。

Nacos示例数据如下

 

代码如下

1、开启 Nacos 配置中心

NacosConfig.java

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

@Configuration
@RefreshScope
@EnableDiscoveryClient
public class NacosConfig
{

}

 

2、开启Nacos配置指定属性

EnableNacosConfig.java

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({PurchaserNameNumProperties.class})
public class EnableNacosConfig
{

}

 

3、属性配置

PurchaserNameNumProperties.java

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

/**
 * @author liuyanzhao
 * @date 2022/3/8 11:19
 */
@Data
@ConfigurationProperties(prefix = "purchaser")
public class PurchaserNameNumProperties
{
    /**
     * 购买方名称和纳税号列表
     */
    private List<String> nameNum;
}

 

4、依赖注入,调用

任意 Spring 扫描的类

@Autowired
private PurchaserNameNumProperties purchaserNameNumProperties;

直接像注入普通 Bean 一样注入即可

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0