第4章 Spring Boot 属性文件配置深入探索:从批量读取到自定义

798 阅读4分钟

在上一篇文章【# Spring Boot多环境配置实战:轻松应对开发、测试与生产】中,我们详细探讨了Spring Boot中配置文件的应用,包括.properties和.yml文件的使用方法,并且介绍了如何根据不同环境(如开发、测试、生产)来灵活地切换配置。本文将在此基础上更进一步,带领大家深入了解如何自定义配置文件以及如何批量读取多个配置文件。我们将通过具体的代码示例,展示如何创建配置属性的Java Bean类,并演示如何在项目中注入这些配置。此外,我们还将探讨配置文件加载的优先级顺序,以及如何利用Spring Boot提供的random.*属性来生成随机数和UUID等动态数据。通过一系列实验实训,读者可以更加直观地理解不同位置放置配置文件所带来的影响,从而更好地掌握Spring Boot应用的配置管理技巧。

任务要求

基于study-springboot工程下的study-springboot-chapter01模块,其他默认。

任务收获

  1. 学会如何在Springboot中使用属性文件
  2. 学会如何在Springboot中使用yml文件
  3. 知晓属性文件和yaml文件系统启动时,加载的优先级顺序
  4. 学会使用random.* 随机属性
  5. 如何读取属性文件或yaml文件中的值
  6. 熟练编写属性文件和yaml文件

环境要求

  1. JDK1.8+
  2. MySQL8.0.27+
  3. Maven 3.6.1+
  4. IDEA/VSCode

工程目录要求

仓库地址:gitee.com/ossbar/stud…

模块:study-springboot-chapter01

任务实施步骤如下:

1、 改造study-springboot-chapter01工程

2、新建HomeProperties Bean类

package com.cbitedu.springboot.config;

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

/**
 * 家乡属性
 *
 * Created by cbitedu on 17/04/2021.
 */
@Component
@ConfigurationProperties(prefix = "home")
public class HomeProperties {

    /**
     * 省份
     */
    private String province;

    /**
     * 城市
     */
    private String city;

    /**
     * 描述
     */
    private String desc;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "HomeProperties{" +
                "province='" + province + ''' +
                ", city='" + city + ''' +
                ", desc='" + desc + ''' +
                '}';
    }
}

3、新建UserProperties Bean类,内容如下:

package com.cbitedu.springboot.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 *  Created by cbitedu on 17/04/2021.
 */
@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {
    /**
     * 用户 ID
     */
    private Long id;

    /**
     * 年龄
     */
    private int age;

    /**
     * 用户名称
     */
    private String desc;

    /**
     * 用户 UUID
     */
    private String uuid;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

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

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }


    @Override
    public String toString() {
        return "UserProperties{" +
                "id=" + id +
                ", age=" + age +
                ", desc='" + desc + ''' +
                ", uuid='" + uuid + ''' +
                '}';
    }
}

4、分别在application.properties中加入

#指定默认的环境配置
spring.profiles.active=dev

在application-dev.properties开发环境中配置

## 家乡属性 Dev
home.province=湖南省
home.city=长沙市
home.desc=dev: 籍贯所在地为${home.province} ${home.city}.
user.age=28
user.desc=张三

在application-prod.properties生产环境中配置

## 家乡属性 Dev
home.province=广东省
home.city=广州市
home.desc=dev: 籍贯所在地为${home.province} ${home.city}.
user.age=82
user.desc=李四

也可以用application.yaml(或用---来分割)一个文件代替

## 家乡属性
home:
  province: 浙江省
  city: 温岭松门
  desc: 我家住在${home.province}的${home.city}

## 随机属性
user:
  id: ${random.long}
  age: ${random.int[1,200]}
  desc: 程序员叫做${random.value}
  uuid: ${random.uuid}

或application.yml代替(application-dev.yml,application-prod.yml)

5、运行com.cbitedu.springboot.property下的PropertiesTest单元测试类

package com.cbitedu.springboot.property;

import com.cbitedu.springboot.config.HomeProperties;
import com.cbitedu.springboot.config.UserProperties;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 读取配置文件测试类
 * <p>
 * Created by cbitedu on 17/04/2021.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesTest.class);

    @Autowired
    private UserProperties userProperties;

    @Autowired
    private HomeProperties homeProperties;

    @Test
    public void getHomeProperties() {
        LOGGER.info("\n\n" + homeProperties.toString() + "\n");
    }

    @Test
    public void randomTestUser() {
        LOGGER.info("\n\n" + userProperties.toString() + "\n");
    }

}

6、小结获取属性文件中的属性

实验实训

体验Springboot属性文件读取的优先级,分别把属性文件至于不同的目录进行测试,通过日志观察和加深优先级概念。

  1. 工程目录下的config目录
  2. resources目录
  3. 工程根目录
  4. resources/config目录

接下来的文章将进一步引导你进入Spring Boot的核心——注解驱动的开发模式。我们将详细介绍Spring Boot中常用的注解,比如@ConfigurationProperties用于绑定配置文件属性到Java Bean对象,@SpringBootApplication用于标记主类,以及@EnableAutoConfiguration如何帮助我们自动配置组件等。通过本篇文章的学习,你将能够更加熟练地运用Spring Boot提供的强大功能,简化应用的配置过程,并提升开发效率。我们将结合实际案例,一步步展示如何使用这些注解来增强你的Spring Boot应用程序,使其更加健壮和易于维护。