Spring Boot系列之读取配置

简介: 使用SpringBoot框架开发,读取配置是少不了的,那么你会读取配置吗?你会写配置吗?List?Map?

使用SpringBoot框架开发,读取配置是少不了的,那么你会读取配置吗?你会写配置吗?List?Map?

1 目的

本节我们要解决如下几个问题:

  • 如何使用Spring Boot读取配置文件?有哪些方式?
  • 常用的几种数据结构,如字符串、整数、List、Map,如何配置?如何读取?
  • 如何自定义配置文件的路径?

2 读配置文件

Spring Boot默认的配置文件有两种格式: application.propertiesapplication.yml

查找顺序是首先从application.properties 查找,如果找不到,再查找 application.yml

优先级: application.properties > application.yml

首先,添加依赖。

Maven:

<!-- spring boot config -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Gradle:

annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'

2.1 使用 @Value 读取配置

配置如下:

erwin.name=冯文议
erwin.age=20
erwin.sex=男
erwin.english-name=Erwin Feng
erwin.birthday=1992/02/26
erwin.like=movie,game,music,tea,travel
erwin.visitedCities=巴中,揭阳,广州,从化,成都,三亚,上海,杭州,北京
erwin.moreOther={myWeb:'https://fengwenyi.com',github:'https://github.com/fengwenyi'}

代码如下:

package com.fengwenyi.spring_boot_config_sample.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * @author Erwin Feng
 * @since 2020/8/11
 */
@Data
@Configuration
public class ReadConfigByValue {

    @Value("${erwin.name}")
    private String name;

    @Value("${erwin.age}")
    private Integer age;

    @Value("${erwin.sex}")
    private String sex;

    @Value("${erwin.english-name}")
    private String englishName;

    @Value("${erwin.birthday}")
    private Date birthday;

    @Value("${erwin.like}")
    private List<String> likes;

    @Value("#{'${erwin.visitedCities}'.split(',')}")
    private List<String> visitedCities;

    @Value("#{${erwin.moreOther}}")
    private Map<String, String> moreOther;
    
}


2.2 使用 @ConfigurationProperties 读取配置

配置如下(properties格式)

author.name=冯文议
author.age=20
author.sex=男
author.english-name=Erwin Feng
author.birthday=1992/02/26
author.like[0]=movie
author.like[1]=game
author.like[2]=music
author.like[3]=tea
author.like[4]=travel
author.visitedCities=巴中,揭阳,广州,从化,成都,三亚,上海,杭州,北京
author.moreOther.myWeb=https://fengwenyi.com
author.moreOther.github=https://github.com/fengwenyi

配置如下(yaml格式)

author:
  name: 冯文议-yml
  age: 20
  sex: 男
  english-name: Erwin Feng
  birthday: 1992/02/26
  like:
    - movie
    - game
    - music
    - tea
    - travel
  visitedCities: 巴中,揭阳,广州,从化,成都,三亚,上海,杭州,北京
  moreOther:
    myWeb: https://fengwenyi.com
    github: https://github.com/fengwenyi


代码如下:

package com.fengwenyi.spring_boot_config_sample.config;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

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

/**
 * @author Erwin Feng
 * @since 2020/8/12
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "author")
public class AuthorConfig implements Serializable {

    private static final long serialVersionUID = 9032405467573421607L;

    private String name;

    private Integer age;

    private String sex;

    private String englishName;

    @JsonFormat(pattern = "yyyy/MM/dd")
    private Date birthday;

    private List<String> like;

    private List<String> visitedCities;

    private Map<String, String> moreOther;

}


读取出来的数据展示:

{
    "name":"冯文议",
    "age":20,
    "englishName":"Erwin Feng",
    "birthday":"1992/02/26",
    "likes":[
        "movie",
        "game",
        "music",
        "tea",
        "travel"
    ],
    "visitedCities":[
        "巴中",
        "揭阳",
        "广州",
        "从化",
        "成都",
        "三亚",
        "上海",
        "杭州",
        "北京"
    ],
    "moreOther":{
        "myWeb":"https://fengwenyi.com",
        "github":"https://github.com/fengwenyi"
    }
}

2.3 通过注入环境变量来获取配置信息

    @Autowired
    private Environment environment;

3 @Value 用法

3.1 设置默认值

格式:@Value("${name:defaultValue}")

当配置文件找不到这个配置时,就会返回默认值,如果没有默认值,就会报错。

3.2 可以直接读取系统的属性值

如:@Value("${java.home}")

D:JavaJava8jdk1.8.0_251jre

3.3 可以用在方法和参数上,当做单元测试

    // 单元测试-读取配置文件的值
    @Value("${erwin.like}")
    public void testReadLike(String like, @Value("${erwin.sex}") String sex) {
        System.out.println("1===>" + like);
        System.out.println("1===>" + sex);
    }

参数 like 会取 @Value("${erwin.like}") 的值
参数 sex 会取 @Value("${erwin.sex}") 的值
经过测试,多个方法,执行顺序是随机。
特别注意:这个只是在启动的时候执行,但是实际调用的时候,还是传入的值。

3.4 读取list的值

方法一:
配置文件:

erwin.like=movie,game,music,tea,travel


Java代码:

@Value("${erwin.like}")
private List likes;

方法二:

erwin.visitedCities=巴中,揭阳,广州,从化,成都,三亚,上海,杭州,北京

Java代码:

@Value("#{'${erwin.visitedCities}'.split(',')}")
private List visitedCities;

3.5 读取Map的值

配置文件:

erwin.moreOther={myWeb:'https://fengwenyi.com',github:'https://github.com/fengwenyi'}

Java代码:

@Value("#{${erwin.moreOther}}")
private Map moreOther;


3.6 读取系统属性

@Value("#{systemProperties}")
private Map systemPropertiesMap;

3.7 给私有属性赋值

@Component
@PropertySource("classpath:values.properties")
public class PriorityProvider {
 
    private String priority;
 
    @Autowired
    public PriorityProvider(@Value("${priority:normal}") String priority) {
        this.priority = priority;
    }
 
    // standard getter
}

4 @ConfigurationProperties

package com.fengwenyi.spring_boot_config_sample.config;

import com.fengwenyi.spring_boot_config_sample.support.YamlPropertySourceFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.Serializable;

/**
 * @author Erwin Feng
 * @since 2020/8/13
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "db")
//@PropertySource({"classpath:config/db.properties"})
@PropertySource(value = {"classpath:config/db.yml"}, factory = YamlPropertySourceFactory.class)
public class DBConfig implements Serializable {

    private static final long serialVersionUID = -6527591545525817929L;

    /** 服务器地址 */
    private String host;

    /** 端口 */
    private Integer port;

    /** 数据库名 */
    private String dbName;

    /** 用户名 */
    private String username;

    /** 密码 */
    private String password;
}

配置文件:

db:
  host: localhost
  port: 3306
  db-name: test
  username: root
  password: 123456

说明:
1、@Configuration 表明这是一个Spring配置,会注入到Spring容器中。
2、@ConfigurationProperties(prefix = "db") 表示这个类与配置文件关联,其中prefix指明前缀。
3、@PropertySource 这个指明配置文件的位置,如果没有这个配置,则会从默认的配置文件读取。默认的配置文件:application.properties > application.yml。另外,这个默认只支持properties类型的文件,所以,需要配置factory。
4、@PropertySource也可以与@Value结合使用。

YamlPropertySourceFactory

package com.fengwenyi.spring_boot_config_sample.support;

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;

/**
 * @author Erwin Feng
 * @since 2020/8/13
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 返回 yaml 属性资源
        return new YamlPropertySourceLoader()
                .load(resource.getResource().getFilename(), resource.getResource())
                .get(0);
    }
}

参考链接

关于

我是冯文议(Erwin Feng),Java Developer,专注于程序设计与开发。开源项目:JavaLib、api-result。喜欢电影、游戏、音乐、茶、旅行。
我的个人网站:https://fengwenyi.com
我的Github:https://github.com/fengwenyi

目录
相关文章
|
2月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
2月前
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
2月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
4月前
|
Java Spring
Spring Boot配置的优先级?
在Spring Boot项目中,配置可通过配置文件和外部配置实现。支持的配置文件包括application.properties、application.yml和application.yaml,优先级依次降低。外部配置常用方式有Java系统属性(如-Dserver.port=9001)和命令行参数(如--server.port=10010),其中命令行参数优先级高于系统属性。整体优先级顺序为:命令行参数 &gt; Java系统属性 &gt; application.properties &gt; application.yml &gt; application.yaml。
952 0
|
1月前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
2月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
535 5
|
2月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
179 0
探索Spring Boot的@Conditional注解的上下文配置
|
7月前
|
安全 Java API
深入解析 Spring Security 配置中的 CSRF 启用与 requestMatchers 报错问题
本文深入解析了Spring Security配置中CSRF启用与`requestMatchers`报错的常见问题。针对CSRF,指出默认已启用,无需调用`enable()`,只需移除`disable()`即可恢复。对于`requestMatchers`多路径匹配报错,分析了Spring Security 6.x中方法签名的变化,并提供了三种解决方案:分次调用、自定义匹配器及降级使用`antMatchers()`。最后提醒开发者关注版本兼容性,确保升级平稳过渡。
898 2
|
8月前
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
1010 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
3月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
981 10

热门文章

最新文章