springboot读取XXX.properties自定义配置文件中的map和list类型配置参数
2021/4/20 18:28:11
本文主要是介绍springboot读取XXX.properties自定义配置文件中的map和list类型配置参数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1. maven的pom.xml文件中添加如下依赖
<!-- 配置文件要用到的jar包 processor --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
2. 配置文件 XXX.properties添加如下参数
说明:配置文件中的前缀需要全部小写,不能出现大写。 例如下面的 data
#map 第一种方式 data.person.name=zhangsan data.person.sex=man data.person.age=11 data.person.url=xxxxxxxx #map 第二种方式 data.person[name]=zhangsan data.person[sex]=man data.person[age]=11 data.person[url]=xxxxxxxx #list 第一种方式 data.list[0]=apple0 data.list[1]=apple1 data.list[2]=apple2 #list 第二种方式 data.list=apple0,apple1,apple2,\ apple3,apple4,apple5
3.写一个DataConfig类,用来读取配置信息
#要注意的地方是 属性名 要与 XXX.properties中的参数的名保持一致,详见属性注解 //@Configuration 标识这是一个配置类 @Component("configData") // 添加到bean容器时指定其名为 configData @ConfigurationProperties(prefix = "data") // 读取前缀为 data 的内容 //如果只有一个主配置类文件,@PropertySource可以不写 @PropertySource("classpath:XXX.properties") // @PropertySource(value = { "classpath:config/XXX.properties" }, encoding = "utf-8") public class DataConfig{ /** * data.person.name * 这里map名需要和XXX.properties中的参数data.person.name的person一 致 */ private Map<String, String> person = new HashMap<>(); /** * data.list * 这里list名需要和XXX.properties中的参数data.list的list一致 */ private List<String> list = new ArrayList<>(); /** * 编写get,set方法方便使用 */ public Map<String, String> getPerson() { return person; } public void setPerson(Map<String, String> person) { this.person = person; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } }
4.测试类测试
@Autowired @Qualifier("configData") // 指定注入bean的名称,提高注入准确性 private DataConfig dataConfig; @Test public void contextLoads() { Map<String, String> person = dataConfig.getPerson(); List<String> list = dataConfig.getList(); System.out.println("image:"+JSONObject.fromObject(person).toString()); System.out.println("list:"+ JSONArray.fromObject(list).toString()); }
输出结果
image:{"sex":"man","name":"zhangsan","age":"11","url":"xxxxxxxx"} list:["apple0","apple1","apple2","apple3","apple4","apple5"]
这篇关于springboot读取XXX.properties自定义配置文件中的map和list类型配置参数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现