SpringBoot(5)——SpringBoot配置文件

发布于:2025-03-17 ⋅ 阅读:(19) ⋅ 点赞:(0)

系列文章

1、SpringBoot(1)——创建SpringBoot项目的方式_基于注解方式开发aspectj springboot下载-CSDN博客

2、SpringBoot(2)——SpringBoot入门:微服务-CSDN博客

3、SpringBoot(3)——SpringBoot入门程序及解析-CSDN博客

4、SpringBoot(4)——SpringBoot自动配置原理-CSDN博客

文章目录

1、配置文件

2、YAML语法

1.基本语法

2.值的写法

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

4.数组(List、Set)

3、配置文件值注入

方式一:@ConfigurationProperties

方式二:@Value

@Value获取值和@ConfigurationProperties获取值比较

方式三:@PropertySource

方式四:@ImportResource

SpringBoot推荐给容器中添加组件的方式

 4、Profile

1、多Profile文件

2、yml支持多文档块方式

3、激活指定profile

4、配置文件加载位置


1、配置文件

SpringBoot使用一个全局的配置文件,配置文件名是固定的;

application.properties

•application.yml

其中:application.properties的优先级高于application.yml

配置文件的作用:

                修改SpringBoot自动配置的默认值;SpringBoot在底层都给我们自动配置好;

YAML(YAML Ain't Markup Language)

YAMLisn't Markup Language:不是一个标记语言;

标记语言

以前的配置文件;大多都使用的是xxxx.xml文件;

YAML:以数据为中心,比json、xml等更适合做配置文件;

大致样子如下:

2、YAML语法

1.基本语法

k: v (注意有空格)

表示一对键值对(空格必须有)

以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的

         属性和值也是大小写敏感;
2.值的写法
字面量:普通的值(数字,字符串,布尔)
k: v字面直接来写
字符串默认不用加上单引号或者双引号。
" "双引号 不会转义字符串里面的特殊字符 ,特殊字符依旧表达特殊含义
name: "zhangsan \n lisi"
输出——   zhangsan
                 lisi
‘ '单引号 会转义特殊字符 ,特殊字符最终只是一个普通的字符串数据
name: ‘zhangsan \n lisi’:
输出—— zhangsan \n lisi
3.对象、Map(属性和值)(键值对)
k: v:在下一行来写对象的属性和值的关系; 注意缩进
对象还是k: v的方式
4.数组(List、Set)
用- 值表示数组中的一个元素
行内写法

3、配置文件值注入

方式一:@ConfigurationProperties

我们先创建一个Person的实体类(这个类很复杂,为了体现不同参数的传参形式)

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
//@Validated
@ConfigurationProperties(prefix = "person")
public class Person {
    //@Email
    String email;
    String hello;
    String lastName;
    int  age;
    boolean Boss;
    
    @DateTimeFormat(pattern = "yyyy/MM/dd")
    Date birth;
    
    Map<String,String> maps;
    List<String> list;
    
    Dog dog;

    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getHello() {
        return hello;
    }
    public void setHello(String hello) {
        this.hello = hello;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isBoss() {
        return Boss;
    }
    public void setBoss(boolean boss) {
        Boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, String> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
    public List<String> getList() {
        return list;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    @Override
    public String toString() {
        return "Person{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                ", Boss=" + Boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
}

参数类Dog

package cn.tx.springboot.model;

public class Dog {
    private String name;
    private int  age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

配置文件application.yml

person:
  email: 22444@aa.com
  lastName: 亮
  age: 18
  Boss: true
  birth: 2018/10/14
  maps: {key1: 02, key2: 01}
  list: [kily,lucy,house]
  dog:
    name: ${person.hello}_dog
    age: ${random.int}
  hello: luky

编写pom文件(我们可以导入配置文件处理器,以后编写配置就有提示了)

<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

编写测试方法

@Controller
public class HelloController {
    @Autowired
    private Person person;


    @ResponseBody  /*返回字符串*/
    @RequestMapping("/hello")
    public String hello(){
        System.out.println("Email: " + person.getEmail());
        System.out.println("Hello: " + person.getHello());
        System.out.println("LastName: " + person.getLastName());
        System.out.println("Age: " + person.getAge());
        System.out.println("Is Boss: " + person.isBoss());
        System.out.println("Birth: " + person.getBirth());
        System.out.println("Maps: ");
        Map<String, String> maps = person.getMaps();
        if (maps != null) {
            maps.forEach((key, value) -> System.out.println(key + ": " + value));
        }
        System.out.println("List: ");
        List<String> list = person.getList();
        if (list != null) {
            list.forEach(System.out::println);
        }
        System.out.println("Dog - Name: " + (person.getDog() != null ? person.getDog().getName() : "null"));
        System.out.println("Dog - Age: " + (person.getDog() != null ? person.getDog().getAge() : "null"));
        return "Hello World!";
    }

}

测试结果如下图:

方式二:@Value

编写Person1实体类

package com.qcby.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Component
@Validated
//@ConfigurationProperties(prefix = "person")
public class Person1 {

    @Email
    @Value("${person.email}")
    String email;

    @Value("${person.hello}")
    String hello;

    @Value("${person.last-name}")
    String lastName;

    @Value("${person.age}")
    int  age;

    @Value("${person.boss}")
    boolean Boss;

    @DateTimeFormat(pattern = "yyyy/MM/dd")
    @Value("${person.birth}")
    Date birth;

    Map<String,String> maps;

    @Value("${person.list}")
    List<String> list;

    Dog dog;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isBoss() {
        return Boss;
    }

    public void setBoss(boolean boss) {
        Boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "Person1{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                ", Boss=" + Boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
}

配置application.properties文件

person.hello=luky
person.email=10199@tt.226m
person.last-name=亮
person.birth=2017/02/4
person.age=19
person.boss=true
person.list=dog,cat,animal
person.maps.key1=kkygjz
person.maps.key2=hhygyz
person.dog.name=${person.hello}_dog
person.dog.age=${person.age}

pom文档添加依赖(我加了@Email规范注解)

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

编写测试类

(map和dog实现不出来,需要再添加逻辑,我这里没写)

@ResponseBody  /*返回字符串*/
@RequestMapping("/hello1")
public String hello1(){

    System.out.println("Email: " + person1.getEmail());
    System.out.println("Hello: " + person1.getHello());
    System.out.println("LastName: " + person1.getLastName());
    System.out.println("Age: " + person1.getAge());
    System.out.println("Is Boss: " + person1.isBoss());
    System.out.println("Birth: " + person1.getBirth());
    System.out.println("Maps: ");
    Map<String, String> maps = person1.getMaps();
    if (maps != null) {
        maps.forEach((key, value) -> System.out.println(key + ": " + value));
    }
    System.out.println("List: ");
    List<String> list = person1.getList();
    if (list != null) {
        list.forEach(System.out::println);
    }
    System.out.println("Dog - Name: " + (person1.getDog() != null ? person1.getDog().getName() : "null"));
    System.out.println("Dog - Age: " + (person1.getDog() != null ? person1.getDog().getAge() : "null"));
    return "Hello World!";
}

测试结果如下:

properties配置文件在idea中默认utf-8可能会乱码

@Value获取值和@ConfigurationProperties获取值比较
配置文件yml还是properties他们都能获取到值;
  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value
  • 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties

方式三:@PropertySource

@PropertySource 注解可以帮助我们将指定的属性文件加载到 Spring 的 Environment 中,这样就可以在应用中方便地使用这些属性。也就是说,创建这个类时,会去找@PropertySource注解中classpath中的配置文件。注意!不支持 YAML 文件

Person2实体类

package com.qcby.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

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

@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person2")
public class Person2 {

    String email;

    String hello;

    String lastName;

    int  age;

    boolean Boss;

    @DateTimeFormat(pattern = "yyyy/MM/dd")
    Date birth;

    Map<String,String> maps;

    List<String> list;

    Dog dog;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isBoss() {
        return Boss;
    }

    public void setBoss(boolean boss) {
        Boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "Person2{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                ", Boss=" + Boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
}

person.properties

server.port=8085

person2.hello=luky 
person2.email=10199@tt.226m
person2.last-name=亮
person2.birth=2017/02/4
person2.age=19
person2.boss=true
person2.list=dog,cat,animal
person2.maps.key1=kkygjz
person2.maps.key2=hhygyz
方式四:@ImportResource

导入Spring的配置文件,让配置文件里面的内容生效;Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来,需要把@ImportResource标注在一个配置类上

Person3实体类编写

package com.qcby.entity;

import org.springframework.context.annotation.ImportResource;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@ImportResource(locations = "classpath:beans.xml")
public class Person3 {


    String email;

    String hello;

    String lastName;

    int  age;

    boolean Boss;

    @DateTimeFormat(pattern = "yyyy/MM/dd")
    Date birth;

    Map<String,String> maps;

    List<String> list;

    Dog dog;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isBoss() {
        return Boss;
    }

    public void setBoss(boolean boss) {
        Boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "Person3{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                ", Boss=" + Boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
}

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">

    <!--将proson3交给ioc的配置文件-->
    <bean id="person3" class="com.qcby.entity.Person3">
        <property name="email" value="256984@qq.com"/>
        <property name="age" value="19"/>
        <property name="birth" value="2017/02/01"/>
        <property name="boss" value="true"/>
    </bean>

</beans>

在主启动类上添加注解

package com.qcby;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

/**
 * @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
 */

/*springboot的@ComponentScan注解,扫描主启动类所在包及其所有子包*/
@ImportResource(locations = "classpath:beans.xml")    
@SpringBootApplication
public class HelloWorldMainApplication {
    public static void main(String[] args) {
        // Spring应用启动起来
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }}

编写测试类

package com.qcby;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest
public class TxDemo4ApplicationTests {

    @Autowired
    ApplicationContext applicationContext;
    @Test
    public void contextLoads() {
        Object bean = applicationContext.getBean("person3");
        System.out.println(bean);
    }

}

结果如下:

SpringBoot推荐给容器中添加组件的方式

推荐使用全注解的方式

1、配置类@Configuration------>Spring配置文件

2、使用@Bean给容器中添加组件

写一个HelloService类

package com.qcby.controller;

public class HelloService {
    // 定义一个方法,用于返回问候语
    public String sayHello() {
        return "Hello, World!";
    }
}

编写配置文件类

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

测试方法编写

@Autowired
    ApplicationContext applicationContext;
    @Test
    public void contextLoads() {
        HelloService helloService = applicationContext.getBean("helloService1", HelloService.class);
        System.out.println(bean);
    }

测试结果如下,可以看到该组件已经被添加:

 4、Profile

1、多Profile文件
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml
默认使用application.properties的配置;
2、yml支持多文档块方式
3、激活指定profile
  1. 在配置文件中指定 spring.profiles.active=dev
  2. 命令行:
  3. java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar--spring.profiles.active=dev;
  4. 可以直接在测试的时候,配置传入命令行参数
  5. 虚拟机参数;
  6. -Dspring.profiles.active=dev
4、配置文件加载位置

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件

配置文件可以存在于以下四个位置

–file:./config/

–file:./

–classpath:/config/

–classpath:/

优先级由高到底,高优先级的配置会覆盖低优先级的配置;

SpringBoot会从这四个位置全部加载主配置文件;互补配置;

在-classpath:/的application.properties.中加入

server.servlet.context-path=/boot3访问根目录