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>
AI 代码解读

Gradle:

annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
AI 代码解读

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'}
AI 代码解读

代码如下:

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;
    
}
AI 代码解读


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
AI 代码解读

配置如下(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
AI 代码解读


代码如下:

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;

}
AI 代码解读


读取出来的数据展示:

{
    "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"
    }
}
AI 代码解读

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

    @Autowired
    private Environment environment;
AI 代码解读

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);
    }
AI 代码解读

参数 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
}
AI 代码解读

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;
}
AI 代码解读

配置文件:

db:
  host: localhost
  port: 3306
  db-name: test
  username: root
  password: 123456
AI 代码解读

说明:
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);
    }
}
AI 代码解读

参考链接

关于

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

目录
打赏
0
0
0
0
43
分享
相关文章
|
3月前
|
深入解析 Spring Security 配置中的 CSRF 启用与 requestMatchers 报错问题
本文深入解析了Spring Security配置中CSRF启用与`requestMatchers`报错的常见问题。针对CSRF,指出默认已启用,无需调用`enable()`,只需移除`disable()`即可恢复。对于`requestMatchers`多路径匹配报错,分析了Spring Security 6.x中方法签名的变化,并提供了三种解决方案:分次调用、自定义匹配器及降级使用`antMatchers()`。最后提醒开发者关注版本兼容性,确保升级平稳过渡。
332 2
|
4月前
|
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
136 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
354 26
微服务——SpringBoot使用归纳——Spring Boot事务配置管理——Spring Boot 事务配置
本文介绍了 Spring Boot 中的事务配置与使用方法。首先需要导入 MySQL 依赖,Spring Boot 会自动注入 `DataSourceTransactionManager`,无需额外配置即可通过 `@Transactional` 注解实现事务管理。接着通过创建一个用户插入功能的示例,展示了如何在 Service 层手动抛出异常以测试事务回滚机制。测试结果表明,数据库中未新增记录,证明事务已成功回滚。此过程简单高效,适合日常开发需求。
190 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
66 0
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— application.yml 中对日志的配置
在 Spring Boot 项目中,`application.yml` 文件用于配置日志。通过 `logging.config` 指定日志配置文件(如 `logback.xml`),实现日志详细设置。`logging.level` 可定义包的日志输出级别,例如将 `com.itcodai.course03.dao` 包设为 `trace` 级别,便于开发时查看 SQL 操作。日志级别从高到低为 ERROR、WARN、INFO、DEBUG,生产环境建议调整为较高级别以减少日志量。本课程采用 yml 格式,因其层次清晰,但需注意格式要求。
237 0
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
253 73
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
1688 17
Spring Boot 两种部署到服务器的方式
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
203 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
100 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等