iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Spring Cloud中怎么自定义外部化扩展机制
  • 453
分享到

Spring Cloud中怎么自定义外部化扩展机制

2023-06-29 07:06:09 453人浏览 安东尼
摘要

这篇文章主要讲解了“spring Cloud中怎么自定义外部化扩展机制”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Cloud中怎么自定义外部化扩展机制”吧

这篇文章主要讲解了“spring Cloud中怎么自定义外部化扩展机制”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Cloud中怎么自定义外部化扩展机制”吧!

spring cloud针对Environment的属性源功能做了增强,

在spring-cloud-contenxt这个包中,提供了PropertySourceLocator接口,用来实现属性文件加载的扩展。我们可以通过这个接口来扩展自己的外部化配置加载。这个接口的定义如下

public interface PropertySourceLocator {      PropertySource<?> locate(Environment environment);}

locate这个抽象方法,需要返回一个PropertySource对象。

这个PropertySource就是Environment中存储的属性源。 也就是说,我们如果要实现自定义外部化配置加载,只需要实现这个接口并返回PropertySource即可。

按照这个思路,我们按照下面几个步骤来实现外部化配置的自定义加载。

自定义PropertySource

既然PropertySourceLocator需要返回一个PropertySource,那我们必须要定义一个自己的PropertySource,来从外部获取配置来源。

GpDefineMapPropertySource 表示一个以Map结果作为属性来源的类。

public class GpDefineMapPropertySource extends MapPropertySource {        public GpDefineMapPropertySource(String name, Map<String, Object> source) {        super(name, source);    }    @Override    public Object getProperty(String name) {        return super.getProperty(name);    public String[] getPropertyNames() {        return super.getPropertyNames();}

扩展PropertySourceLocator

扩展PropertySourceLocator,重写locate提供属性源。

而属性源是从gupao.JSON文件加载保存到自定义属性源GpDefineMapPropertySource中。

public class GpjsonPropertySourceLocator implements PropertySourceLocator {    //json数据来源    private final static String DEFAULT_LOCATioN="classpath:gupao.json";    //资源加载器    private final ResourceLoader resourceLoader=new DefaultResourceLoader(getClass().getClassLoader());    @Override    public PropertySource<?> locate(Environment environment) {        //设置属性来源        GpDefineMapPropertySource jsonPropertySource=new GpDefineMapPropertySource                ("gpJsonConfig",mapPropertySource());        return jsonPropertySource;    }    private Map<String,Object> mapPropertySource(){        Resource resource=this.resourceLoader.getResource(DEFAULT_LOCATION);        if(resource==null){            return null;        }        Map<String,Object> result=new HashMap<>();        JsonParser parser= JsonParserFactory.getJsonParser();        Map<String,Object> fileMap=parser.parseMap(readFile(resource));        processNestMap("",result,fileMap);        return result;    //加载文件并解析    private String readFile(Resource resource){        FileInputStream fileInputStream=null;        try {            fileInputStream=new FileInputStream(resource.getFile());            byte[] readByte=new byte[(int)resource.getFile().length()];            fileInputStream.read(readByte);            return new String(readByte,"UTF-8");        } catch (IOException e) {            e.printStackTrace();        }finally {            if(fileInputStream!=null){                try {                    fileInputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        return null;//解析完整的url保存到result集合。 为了实现@Value注入    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());}

Spring.factories

/META-INF/spring.factories文件中,添加下面的spi扩展,让Spring Cloud启动时扫描到这个扩展从而实现GpJsonPropertySourceLocator的加载。

org.springframework.cloud.bootstrap.BootstrapConfiguration=\  com.gupaoedu.env.GpJsonPropertySourceLocator

编写controller测试

@RestControllerpublic class ConfiGController {    @Value("${custom.property.message}")    private String name;        @GetMapping("/")    public String get(){        String msg=String.fORMat("配置值:%s",name);        return msg;    }}

阶段性总结

通过上述案例可以发现,基于Spring Boot提供的PropertySourceLocator扩展机制,可以轻松实现自定义配置源的扩展。

于是,引出了两个问题。

  • PropertySourceLocator是在哪个被触发的?

  • 既然能够从gupao.json中加载数据源,是否能从远程服务器上加载呢?

PropertySourceLocator加载原理

先来探索第一个问题,PropertySourceLocator的执行流程。

SpringApplication.run

在spring boot项目启动时,有一个prepareContext的方法,它会回调所有实现了ApplicationContextInitializer的实例,来做一些初始化工作。

ApplicationContextInitializer是Spring框架原有的东西, 它的主要作用就是在,ConfigurableApplicationContext类型(或者子类型)的ApplicationContext做refresh之前,允许我们对ConfiurableApplicationContext的实例做进一步的设置和处理。

它可以用在需要对应用程序上下文进行编程初始化的WEB应用程序中,比如根据上下文环境来注册propertySource,或者配置文件。而Config 的这个配置中心的需求恰好需要这样一个机制来完成。

public ConfigurableApplicationContext run(String... args) {   //省略代码...        prepareContext(context, environment, listeners, applicationArguments, printedBanner);   //省略代码    return context;}

PropertySourceBootstrapConfiguration.initialize

其中,PropertySourceBootstrapConfiguration就实现了ApplicationContextInitializerinitialize方法代码如下。

@Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {    List<PropertySource<?>> composite = new ArrayList<>();    //对propertySourceLocators数组进行排序,根据默认的AnnotationAwareOrderComparator    AnnotationAwareOrderComparator.sort(this.propertySourceLocators);    boolean empty = true;    //获取运行的环境上下文    ConfigurableEnvironment environment = applicationContext.getEnvironment();    for (PropertySourceLocator locator : this.propertySourceLocators) {        //回调所有实现PropertySourceLocator接口实例的locate方法,并收集到source这个集合中。        Collection<PropertySource<?>> source = locator.locateCollection(environment);        if (source == null || source.size() == 0) { //如果source为空,直接进入下一次循环            continue;        }        //遍历source,把PropertySource包装成BootstrapPropertySource加入到sourceList中。        List<PropertySource<?>> sourceList = new ArrayList<>();        for (PropertySource<?> p : source) {            sourceList.add(new BootstrapPropertySource<>(p));        }        logger.info("Located property source: " + sourceList);        composite.addAll(sourceList);//将source添加到数组        empty = false; //表示propertysource不为空    }     //只有propertysource不为空的情况,才会设置到environment中    if (!empty) {        //获取当前Environment中的所有PropertySources.        MutablePropertySources propertySources = environment.getPropertySources();        String logConfig = environment.resolvePlaceholders("${logging.config:}");        LogFile logFile = LogFile.get(environment);       // 遍历移除bootstrapProperty的相关属性        for (PropertySource<?> p : environment.getPropertySources()) {                        if (p.getName().startsWith(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {                propertySources.remove(p.getName());            }        }        //把前面获取到的PropertySource,插入到Environment中的PropertySources中。        insertPropertySources(propertySources, composite);        reinitializeLoggingSystem(environment, logConfig, logFile);        setLogLevels(applicationContext, environment);        handleIncludedProfiles(environment);    }}

上述代码逻辑说明如下。

首先this.propertySourceLocators,表示所有实现了PropertySourceLocators接口的实现类,其中就包括我们前面自定义的GpJsonPropertySourceLocator

根据默认的 AnnotationAwareOrderComparator 排序规则对propertySourceLocators数组进行排序。

获取运行的环境上下文ConfigurableEnvironment

遍历propertySourceLocators时

  • 调用 locate 方法,传入获取的上下文environment

  • 将source添加到PropertySource的链表

  • 设置source是否为空的标识标量empty

source不为空的情况,才会设置到environment中返回Environment的可变形式,可进行的操作如addFirst、addLast移除propertySources中的bootstrapProperties根据config server覆写的规则,设置propertySources处理多个active profiles的配置信息

  • 返回Environment的可变形式,可进行的操作如addFirst、addLast

  • 移除propertySources中的bootstrapProperties

  • 根据config server覆写的规则,设置propertySources

  • 处理多个active profiles的配置信息

注意:this.propertySourceLocators这个集合中的PropertySourceLocator,是通过自动装配机制完成注入的,具体的实现在BootstrapimportSelector这个类中。

ApplicationContextInitializer的理解和使用

ApplicationContextInitializer是Spring框架原有的东西, 它的主要作用就是在,ConfigurableApplicationContext类型(或者子类型)的ApplicationContext做refresh之前,允许我们对ConfiurableApplicationContext的实例做进一步的设置和处理。

它可以用在需要对应用程序上下文进行编程初始化的web应用程序中,比如根据上下文环境来注册propertySource,或者配置文件。而Config 的这个配置中心的需求恰好需要这样一个机制来完成。

创建一个TestApplicationContextInitializer

public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{    @Override    public void initialize(ConfigurableApplicationContext applicationContext) {        ConfigurableEnvironment ce=applicationContext.getEnvironment();        for(PropertySource<?> propertySource:ce.getPropertySources()){            System.out.println(propertySource);        }        System.out.println("--------end");    }}

添加spi加载

创建一个文件/resources/META-INF/spring.factories。添加如下内容

org.springframework.context.ApplicationContextInitializer= \  com.gupaoedu.example.SpringCloudconfigserver9091.TestApplicationContextInitializer

在控制台就可以看到当前的PropertySource的输出结果。

ConfigurationPropertySourcesPropertySource {name='configurationProperties'}StubPropertySource {name='servletConfigInitParams'}StubPropertySource {name='servletContextInitParams'}PropertiesPropertySource {name='systemProperties'}OriginAwareSystemEnvironmentPropertySource {name='systemEnvironment'}RandomValuePropertySource {name='random'}MapPropertySource {name='configServerClient'}MapPropertySource {name='springCloudClientHostInfo'}OriginTrackedMapPropertySource {name='applicationConfig: [classpath:/application.yml]'}MapPropertySource {name='kafkaBinderDefaultProperties'}MapPropertySource {name='defaultProperties'}MapPropertySource {name='springCloudDefaultProperties'}

感谢各位的阅读,以上就是“Spring Cloud中怎么自定义外部化扩展机制”的内容了,经过本文的学习后,相信大家对Spring Cloud中怎么自定义外部化扩展机制这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: Spring Cloud中怎么自定义外部化扩展机制

本文链接: https://www.lsjlt.com/news/323475.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring Cloud中怎么自定义外部化扩展机制
    这篇文章主要讲解了“Spring Cloud中怎么自定义外部化扩展机制”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Cloud中怎么自定义外部化扩展机制”吧...
    99+
    2023-06-29
  • Spring Cloud 中自定义外部化扩展机制原理及实战记录
    目录自定义PropertySource扩展PropertySourceLocatorSpring.factories编写controller测试阶段性总结SpringApplicat...
    99+
    2024-04-02
  • PHP怎么自定义扩展
    本篇内容主要讲解“PHP怎么自定义扩展”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“PHP怎么自定义扩展”吧!利用源码工具自动生成扩展目录结构先进入php源码ext目录下执行下面命令/www/t...
    99+
    2023-06-22
  • jquery怎么扩展自定义方法
    要扩展自定义方法,可以使用jQuery的`$.fn`命名空间。下面是一个简单的示例:```javascript// 扩展自定义方法$...
    99+
    2023-08-12
    jquery
  • Spring Cloud中怎么自定义Hystrix请求命令
    Spring Cloud中怎么自定义Hystrix请求命令,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。自定义HystrixCommand我们除了使用@Hyst...
    99+
    2023-06-19
  • Spring XML Schema扩展机制怎么用
    这篇文章主要介绍Spring XML Schema扩展机制怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!前言在当前Java生态,Spring算的上是最核心的框架,所有的开发组件想要得到大范围更便捷的使用,都要和...
    99+
    2023-06-15
  • Spring Cloud中Feign怎么自定义配置与使用
    这篇文章主要介绍了Spring Cloud中Feign怎么自定义配置与使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Spring Cloud中Feign怎么自定义配置与使用文章都会有所收...
    99+
    2023-07-02
  • 怎么自定义一个jQuery扩展接口
    这篇文章给大家介绍怎么自定义一个jQuery扩展接口,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。jQuery是一款很优秀的轻量级JavaScript框架,有其独特的优点。很多Web开...
    99+
    2024-04-02
  • PHP扩展开发:如何将自定义函数与外部语言交互?
    非常抱歉,由于您没有提供文章标题,我无法为您生成一篇高质量的文章。请您提供文章标题,我将尽快为您生成一篇优质的文章。...
    99+
    2024-05-15
  • Spring Cloud gateway自定义错误处理Handler怎么实现
    本文小编为大家详细介绍“Spring Cloud gateway自定义错误处理Handler怎么实现”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Cloud gateway自定义错误处...
    99+
    2023-07-05
  • Spring Cloud OAuth2怎么实现自定义token返回格式
    这篇“Spring Cloud OAuth2怎么实现自定义token返回格式”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我...
    99+
    2023-07-02
  • 怎么在Spring中自定义NamespaceHandler
    今天就跟大家聊聊有关怎么在Spring中自定义NamespaceHandler,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。定义Beanpackage com.lcl.sp...
    99+
    2023-06-14
  • ONNX框架怎么支持自定义算子和扩展
    ONNX框架支持自定义算子和扩展,可以通过编写自定义算子并将其添加到ONNX的运行时中来实现。以下是一些实现自定义算子和扩展的步骤:...
    99+
    2024-04-08
    ONNX
  • 怎么在SAP Cloud for Customer自定义BO中创建访问控制
    本篇内容主要讲解“怎么在SAP Cloud for Customer自定义BO中创建访问控制”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么在SAP Cloud for Customer自定义...
    99+
    2023-06-04
  • 怎么在FrontPage中自定义设置CSS外部样式表
    怎么在FrontPage中自定义设置CSS外部样式表?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。单击”文件“菜单,在弹出的下拉菜单中选择”新建“命令。此时会在程序右侧弹出”新...
    99+
    2023-06-08
  • Spring中自定义拦截器怎么用
    小编给大家分享一下Spring中自定义拦截器怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!创建自定义拦截器类(UserTokenInterceptor)并实...
    99+
    2023-06-29
  • Android中怎么自定义相机
    本篇文章给大家分享的是有关Android中怎么自定义相机,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。使用Android 系统相机的方法:要想让应用有相机的action,咱们就...
    99+
    2023-05-30
    android
  • Spring Boot 中自定义异常怎么处理
    这篇文章将为大家详细讲解有关Spring Boot 中自定义异常怎么处理,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。在 Spring Boot 项目中 ,异常统一处理,可以使用 Spring 中 @Co...
    99+
    2023-06-02
  • jmeter怎么添加自定义扩展函数实现图片base64编码
    这篇“jmeter怎么添加自定义扩展函数实现图片base64编码”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“jmeter怎...
    99+
    2023-06-29
  • Spring MVC中怎么自定义404 Not Found页面
    这篇文章给大家介绍Spring MVC中怎么自定义404 Not Found页面,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。在WEB-INF的web.xml里添加一个新的区域:意思是一旦有404错误发生时,显示res...
    99+
    2023-06-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作