springboot中配置文件的书写与读取方式

1.yml与properties两种配置文件的写法

以下分别展示了普通属性键值对,数组,对象的几种写法
在这里插入图片描述
两种语法的说明
Properties 没有层级关系使用=赋值
Yml 有层级关系 使用: 赋值 (注意冒号后面有空格)

2.通过@Value读取

2.1 普通变量的读取

@Component
public class Mytest {
    
    
    @Value("${person.name}")
    private String name;
}

2.2 静态变量的读取

直接像上面一样,写在变量的上面,是读取不到的

2.2.1 set读取

@Component
public class Mytest {
    
    

    private static String name;
    
    @Value("${person.name}")
    public void setName(String name){
    
    
    	this.name = name;
    }
}

2.2.2 使用@PostConstruct注解

@Component
public class Mytest {
    
    

    private static String NAME;
    
    @Value("${person.name}")
    private Sting name;

    @PostConstruct
    public void init(){
    
    
    	NAME = name;
    }
}

@Value的特别说明

1,如果配置是写在 properties 里面 ——》只有 Map不能取到
2,如果配置写在 yml ——》数组 ,集合 都取不到
3,如果属性是使用驼峰命名法则 不能使用属性名注入

  • 要使用 @Value("${student.user-name}")来取值
  • 不能使用@Value("${student.userName}")来取值

3.使用实体类接受读取

注意下面提供的几个注解,同时,下面是自定义配置文件名的读取。

@Component
@PropertySource("classpath:person.properties")
//读取自定义的properties的值
//当有多个配置文件需要同时读取时使用:@PropertySource({"classpath:config/my.properties","classpath:config/config.properties"})

@ConfigurationProperties(prefix = "person1")
//读取application.properties里面的值
public class Person {
    
    
    private String name;
    private String sex;
    private Integer age;
    private boolean isMerried;
    private List<String> books;
    private String [] pets;
    private List<Friend> friends;
  //get set 方法省略......  
}
@Component
public class Friend {
    
    
    private String name;
    private String sex;
//get set 方法省略......
}

下面是文件目录
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44625080/article/details/109700897