文章目录

  • Spring Boot配置
  • 简单测试使用
  • Spring Cloud自定义配置文件获取
    • 1. 引入依赖
    • 2. 自定义配置
      • 2.1 自定义PropertySource,这里我们直接使用Spring 提供的MapPropertySource
      • 2.2 自定义PropertySourceLocator
      • 2.3 自定义配置Bean config
      • 2.4 定义BootstrapConfiguration配置
    • 3. 测试
  • 总结

这里是weihubeats,觉得文章不错可以关注公众号小奏技术,文章首发。拒绝营销号,拒绝标题党

Spring Boot配置

在spring中我们都知道所有配置定义在配置文件application.yml中我们就可以通过注解获取到。
Spring 中对所有配置管理都有一个统一的上层接口

  • Environment

实现类图

可以看到实现类是非常多的。不过实际所有的配置获取都是封装在最上层的接口PropertyResolver中的

这里需要注意的是PropertyResolver的核心实现类PropertySourcesPropertyResolver

PropertySourcesPropertyResolver中拥有的PropertySources最后使用的也还是PropertySource类,通过遍历PropertySource集合

PropertySource最终是通过拥有一个泛型T source获取最终的属性

所以这里可以看到我们所有的资源都是一个PropertySource
需要注意的是,PropertySource之间是有优先级顺序的,如果有一个Key在多个PropertySource中都存在,那么在前面的PropertySource优先。

大致获取的原理这里引用apollo的一张图

这张图就是比较清晰的

简单测试使用

spring boot 版本 2.6.8

yaml 配置一个name属性

name: 1214
@RestController
public class EnvironementController {@AutowiredEnvironment environment;@Value("${name}")private String name;@GetMapping("/name")public String env(){System.out.println(name);return environment.getProperty("name");}
}

无论是使用@Value还是Environment都能获取到我们的自定义属性

然后调用接口就能获取到我们配置中的属性了

Spring Cloud自定义配置文件获取

在了解了上面的原理及基本使用之后我们可以就可以自定义配置文件了。核心思路就是通过读取文件然后加载到PropertySource中去。
而Spring Cloud刚好提供类这方面的扩展,Spring Cloud 提供了PropertySourceLocator接口供我们加载自定义配置成PropertySource

我们这里只需要实现locate即可

按这个方式我们来自定义配置试试

1. 引入依赖

 <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target>    <spring-cloud.version>2021.0.2</spring-cloud.version><spring-boot.version>2.7.0</spring-boot.version></properties><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-context</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency>      </dependencies></dependencyManagement>

注意spring Cloud 2020版本后需要手动引入依赖 spring-cloud-starter-bootstrap

2. 自定义配置

2.1 自定义PropertySource,这里我们直接使用Spring 提供的MapPropertySource

package com.zou.config;import java.util.Map;import org.springframework.core.env.MapPropertySource;/***@author : wh*@date : 2022/7/12 09:54*@description:*/
public class ZouMapPropertySource extends MapPropertySource {/*** Create a new {@code MapPropertySource} with the given name and {@code Map}.** @param name   the associated name* @param source the Map source (without {@code null} values in order to get*               consistent {@link #getProperty} and {@link #containsProperty} behavior)*/public ZouMapPropertySource(String name, Map<String, Object> source) {super(name, source);}}

2.2 自定义PropertySourceLocator

package com.zou.config;import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;/*** @author : wh* @date : 2022/7/12 09:56* @description:*/
@Order(0)
public class ZouJsonPropertySourceLocator implements PropertySourceLocator {@Overridepublic PropertySource<?> locate(Environment environment) {return new ZouMapPropertySource("ZouMapPropertySource", mapPropertySource());}private Map<String, Object> mapPropertySource() {Map<String, Object> result = new HashMap<>();JsonParser parser = JsonParserFactory.getJsonParser();Map<String, Object> fileMap = parser.parseMap(readFile());processNestMap("", result, fileMap);return result;}/*** 读取配置文件 zou.json** @return*/private String readFile() {List<String> lines;try {lines = Files.readAllLines(Paths.get("src/main/resources/zou.json"), StandardCharsets.UTF_8);}catch (IOException e) {throw new RuntimeException(e);}StringBuilder sb = new StringBuilder();for (String line : lines) {sb.append(line);}return sb.toString();}private void processNestMap(String prefix, Map<String, Object> result, Map<String, Object> fileMap) {if (prefix.length() > 0) {prefix += ".";}for (Map.Entry<String, Object> entrySet : fileMap.entrySet()) {if (entrySet.getValue() instanceof Map) {processNestMap(prefix + entrySet.getKey(), result, (Map<String, Object>) entrySet.getValue());}else {result.put(prefix + entrySet.getKey(), entrySet.getValue());}}}}

2.3 自定义配置Bean config

@Configuration(proxyBeanMethods = false)
public class ZouConfiguration {@Beanpublic ZouJsonPropertySourceLocator zouJsonPropertySourceLocator(){return new ZouJsonPropertySourceLocator();}
}

2.4 定义BootstrapConfiguration配置

resources 添加spring.factories配置文件

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.zou.config.ZouConfiguration

3. 测试

这里简单定义一个我们自己的配置文件zou.json

{"name": "xiaozou"
}

定义一个测试controller

@RestController
@RequestMapping("test/v1")
public class ZouController {@AutowiredEnvironment environment;@Value("${name:1}")private String name;@GetMapping("/name")public String env(){System.out.println(name);return environment.getProperty("name");}
}


可以看到我们自定义配置是生效了的

总结

Spring Cloud 整合自定义配置还是比较容易的,核心还是自定义一个ZouJsonPropertySourceLocator然后加载PropertySource到Spring中。这里我们整合的是本地文件,其实如果要整合远程配置中心也是类似的,只不过获取文件就不是读取本地配置文件,而是通过http读取远程配置文件然后构造出一个PropertySource放入Spring容器中。后续有机会我们对nacos整合Spring Cloud源码进行分析

Spring Boot、Spring Cloud 自定义配置文件(如何整合配置中心)相关推荐

  1. Spring Boot基础学习笔记04:Spring Boot加载自定义配置文件

    文章目录 零.学习目标 1.熟悉使用@PropertySource加载配置文件 2.熟悉使用@ImportResource加载XML配置文件 3.掌握使用@Configuration编写自定义配置类 ...

  2. spring Boot 2 基础篇 。内含 整合一个spring boot 的 小案例

    目录 springBoot2基础篇 前言与开发环境 一.快速创建Boot项目 1.使用spring提供的快速构建 2.基于maven的手动构建 3.在Idea中隐藏指定文件/文件夹 二.SpringB ...

  3. Spring Boot+Spring Cloud实现itoken项目

    itoken项目简介 开发环境 操作系统: Windows 10 Enterprise 开发工具: Intellij IDEA 数据库: MySql 5.7.22 Java SDK: Oracle J ...

  4. Spring - Spring Boot Spring Cloud

    Spring -> Spring Boot > Spring Cloud 这几天刚刚上班,公司用的是Spring Cloud,接触不多.我得赶快学起来. 想学习就必须得知道什么是微服务,什 ...

  5. Spring Boot(17)配置文件解析

    Spring Boot(17)配置文件解析 前言 上一篇介绍了Spring Boot的入门,知道了Spring Boot使用"习惯优于配置"(项目中存在大量的配置,此外还内置了一个 ...

  6. Spring Boot(2) 配置文件

    Spring Boot(2) 配置文件 学习视频:https://www.bilibili.com/video/BV19K4y1L7MT?p=20 1.properties 语法:同以前的proper ...

  7. Spring Boot + Spring Cloud 实现权限管理系统 配置中心(Config、Bus)

    技术背景 如今微服务架构盛行,在分布式系统中,项目日益庞大,子项目日益增多,每个项目都散落着各种配置文件,且随着服务的增加而不断增多.此时,往往某一个基础服务信息变更,都会导致一系列服务的更新和重启, ...

  8. 解决Spring boot中读取属性配置文件出现中文乱码的问题

    解决Spring boot中读取属性配置文件出现中文乱码的问题 参考文章: (1)解决Spring boot中读取属性配置文件出现中文乱码的问题 (2)https://www.cnblogs.com/ ...

  9. Spring Boot Spring Cloud 区分 开发环境 测试环境 预发布环境(灰度环境) 正式环境

    各环境的区别 开发环境(dev):开发的时候用的环境 测试环境(test):日常测试或者是上线前测试. 预发布环境(灰度环境)(pre):发布前的最后调试,数据源与正式环境一致. 正式环境(prod) ...

最新文章

  1. 【怎样写代码】对象克隆 -- 原型模式(三):原型模式
  2. 必须了解的mysql三大日志-binlog、redo log和undo log
  3. c语言不允许对数组的大小做动态定义,数组,C语言程序设计课件,与中南大学出版社教材相配套.ppt...
  4. 中国电信与华为签物联网合作协议
  5. 【caffe-Windows】训练自己数据——数据集格式转换
  6. HashMap jdk1.7源码阅读与解析
  7. 传统数仓不够怎么办?不妨看看这个银行的混合数仓实践,建议收藏
  8. JS字符转为json对象
  9. jenkins+maven+svn+npm自动发布部署实践
  10. Alpha测试与Beta测试
  11. 自然常数e是什么?它是怎么来的?
  12. 在vue中使用videoJs实现前端视频流
  13. 中国科学技术大学2021计算机考研分数线,【中国科学技术大学】2021考研复试分数线3月13日已公布!速看!...
  14. 853计算机综合基础包括什么,2017年南京农业大学853计算机专业基础综合硕士研究生参考书目...
  15. BUG之母——美国海军首位女少将传奇
  16. java-php-python-爱心公益网站设计与制作计算机毕业设计
  17. 位移运算(左移,右移)
  18. 人工智能赋能于企业?来自英特尔的几点建议
  19. 【恩墨学院】京东618大促网关承载十亿调用量背后的架构实践
  20. 计算机英语kbc,计算机英语词汇(附;翻译).doc

热门文章

  1. 笔记本选购2018.9
  2. 如何快速恢复误删文件?文件误删的恢复方法-附软件
  3. vue3.0 引入i18n 做国际化 - 做动态语言切换
  4. 一个体育生的编程之路(一)
  5. 京东2020校招笔试题-算法工程师
  6. zynq linux如何使用pl ip,ZYNQ+linux网口调试笔记(3)PL-ETH
  7. 朝花夕拾《精通CSS》一、HTML CSS 的基础
  8. gta5在线模式服务器暂停使用,R星官网放出《GTAOL》停服公告,12月16日正式关闭线上服务器!...
  9. 嵌入式linux技能,学IT技能 学嵌入式Linux必知内容
  10. Leetcode 130. 被围绕的区域