Properties配置加载(@PropertySource),额外不定的配置项单独存储到Map的一次歧路记录和正确解决思路

本文主要是介绍Properties配置加载(@PropertySource),额外不定的配置项单独存储到Map的一次歧路记录和正确解决思路,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 背景

笔者的一个微服务的配置是ini文件中存储的。通过下面的方式加载。

@Data
@EqualsAndHashCode(callSuper = true)
@Component
@PropertySource(value={"file:${app.config.common.path}" , "file:${app.config.path}"} , ignoreResourceNotFound=false, encoding="utf-8" , name="app-config" , factory = PropertiesExSourceFactory.class)
public class AppConfig extends AppConfCommon
{	@Value("${authcenter.appkey}")String authCenterAppKey ;@Value("${authcenter.appsecret}")String authCenterAppSecret ;@Value("${sailPyAi.url}")String sailPyAiUrl ;}

现在有一些必定数量的参数,它们都以固定的前缀开始,例如

ai.models.glm-4=xxxx
ai.models.bigwatt=xxx

想把ai.models.*的配置都收集到一起

2. 错误的尝试

此尝试,虽然失败,但里面有一些信息觉得有必要记录一下。
过程:

  1. 定义一个Map
public class AppConfig extends AppConfCommon
{	@Value("${authcenter.appkey}")String authCenterAppKey ;@Value("${authcenter.appsecret}")String authCenterAppSecret ;@Value("${sailPyAi.url}")String sailPyAiUrl ;@Value("${ai.models.*:}")Map<String, Object> aiModels ;
}
  1. 修改PropertiesExSourceFactory,在渠道.*结尾的数据时构造成一个Map返回。
	static class  PropertiesExSource  extends EnumerablePropertySource<PropertiesEx>{public PropertiesExSource(String name, PropertiesEx source) {super(name , source) ;}@Overridepublic Object getProperty(String aName){String propValue = getSource().getProperty(aName) ;if(propValue == null && aName.endsWith(".*")){// 检查键String name = aName.substring(0, aName.length()-1) ;Map<String , Object> map = CS.hashMap() ;PropertiesEx source= getSource() ;for(String propName : source.stringPropertyNames()){if(propName.startsWith(name))map.put(propName , source.getProperty(propName)) ;}if(!map.isEmpty())// 因为Spring框架对@PropertySource源,认为取得的值类型一定是String,返回map会报Map转String错误。// 所以此处把Map转成String格式return new JSONObject(map).toJSONString() ;}return propValue ;}@Overridepublic String[] getPropertyNames(){return getSource().stringPropertyNames().toArray(XArray.sEmptyStringArray) ;}}
  1. 因为目标类型是Map,所以需要一个将JSON字符串转成Map的Converter
public class JsonStrToMapConverter implements Converter<String, Map<String, Object>>
{public JsonStrToMapConverter(){}@Overridepublic Map<String, Object> convert(String source){return XString.isEmpty(source)?CS.hashMap():new JSONObject(source).toMap() ;}
}

4.注册这个Converter
因为配置文件加载较早,所以用下面的方式添加Converter

public class DefaultAppRunLsn implements ApplicationListener<ApplicationEvent>
{	// 省略@Overridepublic void onApplicationEvent(ApplicationEvent event){if(event instanceof ApplicationPreparedEvent){ConfigurableApplicationContext ctx = ((ApplicationPreparedEvent)event).getApplicationContext() ;ConversionService cs = ctx.getBeanFactory().getConversionService() ;if(cs instanceof ConverterRegistry){ConverterRegistry reg = (ConverterRegistry)cs ;reg.addConverter(new JsonStrToMapConverter());}// 省略}else if(event instanceof ServletWebServerInitializedEvent){// 省略}}
}

这么做,如果只有一个PropertySource,没有问题,但是有多个的时候,会有问题,原因就是用@Value方式注入,多个PropetySource在一个池子里了,第2步中的getSource()不一定是当前@value字段所在的那个PropertySource了。

3. 正确做法

单独在定义一个配置类。如下:

@Component
@PropertySource(value="file:${app.config.path}" , ignoreResourceNotFound=false, encoding="utf-8" , name="ai-models" , factory = PropertiesExSourceFactory.class)
@ConfigurationProperties(prefix = "ai")
public class AiModelsConf
{Properties models ;public Properties getModels(){return mConf;}public void seModels(Properties aConf){mConf = aConf;}
}

这篇关于Properties配置加载(@PropertySource),额外不定的配置项单独存储到Map的一次歧路记录和正确解决思路的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/974438

相关文章

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

mybatis和mybatis-plus设置值为null不起作用问题及解决

《mybatis和mybatis-plus设置值为null不起作用问题及解决》Mybatis-Plus的FieldStrategy主要用于控制新增、更新和查询时对空值的处理策略,通过配置不同的策略类型... 目录MyBATis-plusFieldStrategy作用FieldStrategy类型每种策略的作

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

Goland debug失效详细解决步骤(合集)

《Golanddebug失效详细解决步骤(合集)》今天用Goland开发时,打断点,以debug方式运行,发现程序并没有断住,程序跳过了断点,直接运行结束,网上搜寻了大量文章,最后得以解决,特此在这... 目录Bug:Goland debug失效详细解决步骤【合集】情况一:Go或Goland架构不对情况二:

解决jupyterLab打开后出现Config option `template_path`not recognized by `ExporterCollapsibleHeadings`问题

《解决jupyterLab打开后出现Configoption`template_path`notrecognizedby`ExporterCollapsibleHeadings`问题》在Ju... 目录jupyterLab打开后出现“templandroidate_path”相关问题这是 tensorflo

如何解决Pycharm编辑内容时有光标的问题

《如何解决Pycharm编辑内容时有光标的问题》文章介绍了如何在PyCharm中配置VimEmulator插件,包括检查插件是否已安装、下载插件以及安装IdeaVim插件的步骤... 目录Pycharm编辑内容时有光标1.如果Vim Emulator前面有对勾2.www.chinasem.cn如果tools工

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

关于Spring @Bean 相同加载顺序不同结果不同的问题记录

《关于Spring@Bean相同加载顺序不同结果不同的问题记录》本文主要探讨了在Spring5.1.3.RELEASE版本下,当有两个全注解类定义相同类型的Bean时,由于加载顺序不同,最终生成的... 目录问题说明测试输出1测试输出2@Bean注解的BeanDefiChina编程nition加入时机总结问题说明

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的