关于Spring Boot项目的配置文件相关内容

本文介绍了YAML和XML两种配置文件的语法,包括键值对、对象、数组的表示方式。在SpringBoot中,@ConfigurationProperties用于批量绑定配置文件属性,而@Value则用于单独获取值。文章还提到了@PropertySource和@ImportResource的使用场景,以及SpringBoot配置文件加载位置和优先级。最后,讨论了SpringBoot的自动配置原理。
摘要由CSDN通过智能技术生成

配置文件可以写.yml(.yaml)或者.xml

一、yaml语法

key: value 表示一堆键值对(注意key和value中间有空格

以空格的缩进控制层级关系

属性和值之间也有空格

属性和值 大小写敏感

server:

        port: 8081

 .xml的写法

<server>

        <port>8081</port>

</server>

yml是以数据为中心,比json和xml更适合做配置文件 

 二、值的写法

字面量:普通的值(数字,字符串,布尔类型)

key: value: //空格

字符串默认不用加引号

双引号""的含义是实现转义字符会原意输出

单引号''的含义转义字符会原样输出

对象、Map(属性和值)(键值对)

 friends

        lastName:(空格) 

        age:

另一种写法

friends: {lastName: zhangsan,age: 18} 

数组(List Set)

用“- 值”表示数组中的一个元素

pets:

 - cat

- dog

另一种写法

pets: [cat,pig,dog]

 配置文件获取值得三种方式

举例说明:

先写两个实体类Preson和Dog

Person类

package com.atguigu.springboot.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties告诉springBoot将本类中的所有属性和配置文件中相关的配置进行绑定
 * (prefix = "person")配置文件下面的所有属性进行一一映射,声明是person类下面的
 * 只有这个组件是容器中的组件 才能提供@ConfigurationProperties功能,把容器加入组件用的是 @Component
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
//    @Value("${person.last-name}")也可以 以这种方式 获取值 
//    不能与@ConfigurationProperties一起使用,不推荐因为要一个一个获取
    private String lastName;
//    @Value("${11*2}")
    private  Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object>maps;
    private List<Object> lists;
    private Dog dog;

    @Override
    public String toString() {
        return "Person{" +
                "lastname'" + lastName + '\'' +
                ",age=" + age +
                ",boos=" + boss +
                ",birth=" + birth +
                ",maps=" + maps +
                ",lists=" + lists +
                ",dog=" + dog +
                '}';

    }


    public String getLastName(){
        return lastName;
    }
    public void setLastName(String lastName){
        this.lastName=lastName;
    }
    public  Integer getAge(){
        return age;
    }
    public void setAge(Integer age){
        this.age=age;
    }
    public  Boolean getBoss(){
        return boss;
    }
    public void setBoss(Boolean boss){
        this.boss=boss;
    }
    public Date getBirth(){
        return birth;
    }
    public void setBirth(Date birth){
        this.birth=birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }
    public void setMaps(Map<String,Object>maps){
        this.maps=maps;
    }
    public List<Object> getLists(){
        return lists;
    }
    public void setLists(List<Object>lists){
        this.lists=lists;
    }
    public Dog dog(){
        return dog;
    }
    public void setDog(Dog dog){
        this.dog=dog;
    }
}

@Value和@ConfigurationProperties的区别 

@PropertySource和@ImportResource

由于@ConfigurationProperties默认是从全局配置文件(.yaml/.yml/.xml)中提取值,如果把所有的值放入配置文件,会导致配置文件过大的问题,所以可以用@PropertySource

举个例子:把application.properties中关于person的值放入一个新的配置文件person.properties中我们可以通过@PropertySource

@PropertySource(value = {"classpath:person.properties"})

类路径下的person.properties

@ImportResource:导入配置文件 并且 让spring中的配置文件生效

举例说明 先在Service包下创建一个HelloService.java

创建一个Spring的配置文件 Beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="HelloService" class="com.atguigu.springboot.service.HelloService">

</bean>
</beans>

做一个测试,测试一下容器中有没有我们自己写的HelloService

测试类写入代码,判断是否存在

@Autowired //@Autowired 是一个注释,它可以对类成员变量、方法及构造函数进行标注,让 spring 完成 bean 自动装配的工作。
    ApplicationContext ioc;//ApplicationContext就是IOC容器,是提供IOC容器应用配置的普通接口
    @Test //测试容器中中有没有HelloService 如果有返回true 没有返回false
    public void testHelloService(){
     boolean b  = ioc.containsBean("HelloService");
     System.out.println(b);
    }

结果如图,返回false

spring Boot中自己写的的配置文件不会被自动识别 所以系统中是没有HelloService

所以让配置文件生效,需要加载@ ImportResource

在Service包下系统帮我创建的(在创建HelloService时)配置类中添加以下语句
@ImportResource(locations = {"classpath:beans.xml"} )

 我们再来测试一下 发现输出了 true 这就说明容器中已经有了 HelloService

之前添加组件的方式就是创建配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="HelloService" class="com.atguigu.springboot.service.HelloService"/>


</beans>

但这种方式是不推荐

Spring Boot推荐用全注解的方式添加组件

创建一个配置类或者 可以用 主配置类

package com.atguigu.springboot.config;

import com.atguigu.springboot.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 *
 *@Configuration指明当前类是一个配置类,就是用来代替之前怕【配置的Spring配置文件
 *之前在配置文件中添加的是<bean></bean>标签
 **/
@Configuration
public class MyAppConfig {
    //将方法的返回值添加到容器,容器中这个组件默认id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean给容器添加了组件了");
        return new HelloService();
    }
}

Dog类 

package com.atguigu.springboot.bean;

public class Dog {
    private String name;
    private Integer age;

    @Override
    public String toString(){
        return "Dog{" +
                "name='" + name + '\'' +
                ",age=" + age +
                '}';
    }

    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }
    public  Integer getAge(){
        return age;
    }
    public void setAge(Integer age){
        this.age=age;
    }
}

.yml配置文件获取值

server:
  port: 8081



Person:
   lastName:hello
   age:18
    boss:false
    birth:2017/12/12
maps: {k1: v1,k2: 12}
lists:
    - lisi
    - zhaoliu
dog:
    name:旺财
    age:9

遇到的问题

Caused by: org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping
 in 'reader', line 1, column 1:
    server:
    ^
expected <block end>, but found '<block sequence start>'
 in 'reader', line 14, column 4:
       - zhaoliu
       ^

java.lang.IllegalStateException: Failed to load ApplicationContext

这个是因为.yml在获取值的时候格式没有写正确,比如没有纵向对齐...

明明写了值,为什么会输出null呢?

输出结果:Person{lastname'null',age=null,boos=null,birth=null,maps=null,lists=null,dog=null}

.xml配置文件获取值

server.port=8081
配置person的值
person.last-name=张三
person.age=18
person.birth=2017/12/17
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=旺财
person.dog.age=9

遇到的问题

如果输出时在last-name,dog.name出现乱码,可以在Setting→File Encodings设置 如图

 如果还是乱码,需要重新输入person.last-name=张三/person.dog.name=旺财

还可以在中文上+引号(不推荐)

profile

用profile可以切换多个不同的环境

1.多Profile文件

创建两个.properties文件

命名规则是aoolication-(profile).properties/yml

 

每一个这样的文件都可以进行配置,比如端口号等

2.yml支持多文档方式

以“---”分隔文档

每个文档中可以有具体的配置

  spring:
    profiles:
      active:  dev

//激活dev配置文档

3.激活指定profile

1.前提是指定在application.properties(主配置文件中进行激活)

#spring.profiles.active=profile 对应上面的文件名
#spring.profiles.active=dev
spring.profiles.active=prod

2. 命令行的方式激活

 命令行:--spring.profiles.active=dev(具体的profiles)

 3.虚拟机激活参数

与命令行类似

在VM options中 写入命令:-Dspring.profiles.active=dev(具体的profiles)

配置文件加载位置 

-file:./config/ 在项目下创建config包下创建配置文件

-file:./            直接在项目下创建配置文件

-classpath:/config/  也就是resource目录下 常见config包下的配置文件

-classpath:/             resource目录下

 优先级从高到低,高优先级会覆盖低优先级,会互补配置

可以通过spring.config.location来改变默认的配置文件位置

指定的配置文件会和之前的配置文件共同生效

打包好jar包以后,需要更改少量配置可以用到,可以先写好配置文件,然后指定即可

自动配置原理

1.SpringBoot启动会自动加载大量的自动配置类

2.我们可以看我们需要功能有没有SpringBoot自动写好的默认配置类

3.我们再来看自动配置类中,到底配置了哪些组件:(只要我们要用的组件有,我们就不需要再来配置了)

4.给容器中自动配置类添加组件的时候,会从properties类中获取某些属性,我们可以在配置文件中指定这些属性的值

****AutoConfiguration自动配置类:

给容器添加属性

****Properties封装配置文件中的相关属性

自动配置类必须在一定条件下才能生效

我们怎么知道哪些自动配置类生效了

我们可以通过启用 debug=true属性,来让控制台打印自动配置报告,这样就可以知道哪些自动配置类生效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值