SpringBoot配置⽂件的读取(包括list、map类型)
前⾔
添加配置⽂件处理器的依赖,这样在编写配置⽂件的时候就会有提⽰了。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
有了依赖,可以直接使⽤application.properties⽂件为我们⼯作了,这是Springboot的默认⽂件,它会通过其机制读取到上下⽂中,这样就可以引⽤它了
读取配置⽂件
在使⽤maven项⽬中,配置⽂件会放在resources根⽬录下。
我们的springBoot是⽤Maven搭建的,所以springBoot的默认配置⽂件和⾃定义的配置⽂件都放在此⽬录。
springBoot的 默认配置⽂件为 application.properties 或 l,这⾥我们使⽤ application.properties。
web服务器和数据库⾸先在application.properties中添加我们要读取的数据。
server.port = 8081
custom.name = lonewalker
custom.age = 18
第⼀种⽅式
我们可以通过@Value注解,这是Spring就有的,使⽤${...}占位符来读取配置在属性⽂件中的内容,既可以加在属性也可以加在⽅法上
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
@Value("${custom.name}")
private String name;
private Integer age;
public String getName() {
return name;
}
kafka是消息中间件吗public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
@Value("${custom.age}")
public void setAge(Integer age) {个人博客的特点
this.age = age;
}
}
mysql是什么品牌我们在测试环境试⼀下:
@SpringBootTest
class DemoApplicationTests {
@Autowired
User user;
@Test
void contextLoads() {
System.out.Name());
System.out.Age());
}
}
第⼆种⽅式:
如果有很多我们就要写很多@Value,就会很⿇烦,于是就有第⼆种⽅式
通过注解@ConfigurationProperties(prefix="配置⽂件中的key的前缀")可以将配置⽂件中的配置⾃动与实体进⾏映射,默认从全局配置⽂件中获取值。
@ConfigurationProperties("custom")这⾥的字符串database会和类中的属性名称组成全限定名去配置⽂件中查
@Component
@ConfigurationProperties(prefix = "custom")
public class User {
private String name;
private Integer age;
getter()... setter()...
}
扩展:
main unit是什么意思
1、如何获取list数据
test.list=aaa,bbb,ccc
⼜该如何读取呢?
@SpringBootTest
class DemoApplicationTests {
@Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}")
private List<String> testList;
@Test
void contextLoads() {
if (testList == null){
System.out.println("empty");
}else{
for (String list:testList
) {
System.out.println(list);
}
}
}
}
⾸先这是⼀个EL表达式,${test.list:} 是为它加上默认值,但是这样有个问题,当不配置该 key 值,默认值会为空串,它的 length = 1,这样解析出来 list 的元素个数就不是空了
所以在此之前先判断⼀下是否为空,最终写成这样@Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}") 就完美了,遍历的结果
2、如何获取map数据
test.map={name:"守约",force:"95"}
properties是什么文件

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。