springboot读取.properties配置文件中的map和list类型配置参数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot读取.properties配置文件中的map和list类型配置参数相关的知识,希望对你有一定的参考价值。

参考技术A #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

SpringBoot读取properties文件配置项

使用SpringBoot开发过程中,难免需要配置相关数据项,然后在Java代码中@Autowired注入并使用。

我们应该如何读取properties文件中的配置项呢?

基于SpringBoot项目,配置项一般都存放在application.properties文件中。有2种常用的方法:

1.使用@Value注解标注在Field上面
2.使用@ConfigurationProperties注解标注在类或者方法上

为了讲解方便,附上application.properties文件配置好的数据项

如下图所示:

我们可以看到1~3行的配置项,有一个共同的特点:有相同的前缀spring.datasource,既然具备这个特点,那么我们就可以定义一个class,里面有3个fields:userName、password和url。然后在类上使用@ConfigurationProperties标注并指定前缀spring.datasource即可。最后,且非常重要的是,SpringBoot的主入口类 XxxApplication类需要使用@EnableAutoConfiguration进行标注(在SpringBoot 2.x可省略)!

下面附上示例:

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties {
 
 private String userName;
 
 private String password;
 
 private String url;
 
}

那么,类似第5行的 web.upload.path配置项,又应该如何读取呢?

其实,我们可以使用@Value完成属性值注入field。参见以下代码块:

@Value("${web.upload.path}")
private String webUploadPath;

 

完...

以上是关于springboot读取.properties配置文件中的map和list类型配置参数的主要内容,如果未能解决你的问题,请参考以下文章

springboot读取自定义properties配置文件方法

Springboot读取properties配置文件数据

SpringBoot读取.yml/.properties配置文件

Springboot打成JAR包后读取外部配置文件

SpringBoot读取配置文件(从classpath/file读取yml/properties文件)

SpringBoot:四种读取properties文件的方式