Spring Boot 学习(一)properties和yml 配置文件的配置

properties

通过对pojo类进行@Component放入容器中,

之后通过@ConfigurationProperties(prefix = "person")  进行容器前缀绑定,前缀为person

package spring.main.spring.Bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

@ToString
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@ConfigurationProperties(prefix = "person")   //配置文件进行绑定,以person开头
public class Person {
    private String name;
    private Integer age;
    private String[] hobit;
    private Car car;
    private List<String> animal;
    private Map<String,Object> score;
    private Set<Double> salary;
    private Map<String,List<Car>> allCar;
}

 

yml 

  yml中写值需要 key: value   (键+冒号+空格+值)

person:
  name: 张三
  age: 18

#  hobit: [123,456,789]  #数组表示法
  hobit:
    - 123
    - 456
    - 789
#    采用数组的写法或 - value的写法

  animal:
    - 自行车
    - 豆腐干
    - 绕太阳

#  score:
#    English: 90
#    Math: 80
  score: {English: 90,Math: 80}    #对象表示法
  salary:
    - 9999
    - 8888

  car:
    brand: YYY
    price: 123456
#    car是person里的属性,car本身又是属于一个类,所以把类属性写里面
  allCar:
    bads:
      - {brand: RRR,price: 55555}   #数组里面有一个对象
      - brand: EEE
        price: 666666
#      两种写法
    goods:
      - {brand: ppp,price: 55555}

显示:

@Autowired
    Person person;
    @RequestMapping("/person")
    public Person person() {
        return person;
    }

 

 

 

person.name = zs
#通过properties进行配置信息,当yml和properties同时配置时,默认有效原则显示properties

 

 


补充(一)
在yml中,如果对value进行双引号引起来,那么特殊字符会进行转义,例如换行符 \n会显示换行符

 

 

没有引号时和单引号时 会保留原本的\n不会进行转义

 

补充(二)yml中添加提示信息
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
</dependency>

再加上,使打包成jar使不会导入这个提示的功能,减少jvm的加载负重

<configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configurationprocessor</artifactId>
                        </exclude>
                    </excludes>
</configuration>

 

 

 

 

 



posted @ 2021-06-28 11:41  YuyuFishSmile  阅读(229)  评论(0)    收藏  举报