Springboot xxx.properties配置文件配置list属性(2021-07-01)

本文介绍如何在SpringBoot项目中使用YAML配置文件,并通过@Value注解读取list类型的配置项。示例展示了如何配置Redis数据库列表并在Java代码中注入及解析。

Springboot项目是支持yaml格式的配置文件的。yaml格式配置文件比较强大,可以配置列表、对象等属性,但是propertis配置文件功能比较弱,默认是无法支持list属性的,但是我们可以配合Springboot@Value注解一起使用来读取list配置文件。

比如最近的一个需求是在Springboot项目中使用多个Redis数据库。打算将需要的数据库编号以一个列表的形式组织配置。

# redis数据库列表
spring.redis.databases=1,2,3,4,5

Java代码

// 注入属性并解析。
//在@Value注解中可以使用简单的Java代码。具体格式如下:双引号内部是#{}的结构。该结构内部只能写单引号。或者转义后的双引号,如【@Value("#{'${spring.redis.databases}'.split(\",\")}")】
@Value("#{'${spring.redis.databases}'.split(',')}")
private List<Integer> list;

// 测试输出
@Test
void getList(){
    for (int i: list){
        System.out.println("i = "+i);
    }
}

尽量不要使用此种方式解析数据。因为属性注入在方法外面,无法捕获异常,如果配置项写错会导致项目异常。

Spring Boot 中,读取 `application.yml` 或 `application.properties` 文件中的属性信息是非常常见的需求。Spring Boot 提供了多种方式来实现这一功能,下面将详细介绍几种主流方式,并附上示例代码。 --- ## ✅ 一、使用 `@Value` 注解读取单个属性 ### 示例: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyComponent { @Value("${sky.jwt.admin-secret-key}") private String adminSecretKey; public void printAdminSecretKey() { System.out.println("Admin Secret Key: " + adminSecretKey); } } ``` ### ✅ 说明: - `@Value("${属性名}")` 用于从配置文件中注入单个属性值。 - 支持从 `application.yml` 或 `application.properties` 中读取。 - 可以配合默认值使用,例如: ```java @Value("${sky.jwt.admin-secret-key:defaultSecret}") ``` --- ## ✅ 二、使用 `@ConfigurationProperties` 绑定整个配置对象(推荐) 这种方式适合将一组相关的配置项映射为一个 Java Bean。 ### 示例类: ```java import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "sky.jwt") @Data public class JwtProperties { private String adminSecretKey; private long adminTtl; private String adminTokenName; private String userSecretKey; private long userTtl; private String userTokenName; } ``` ### application.yml 示例: ```yaml sky: jwt: admin-secret-key: admin123456 admin-ttl: 3600000 admin-token-name: adminToken user-secret-key: user123456 user-ttl: 86400000 user-token-name: userToken ``` ### ✅ 说明: - `@ConfigurationProperties(prefix = "xxx")` 将指定前缀下的所有属性映射到该类的字段。 - 需要引入 `spring-boot-configuration-processor` 来获得配置提示(可选)。 - 需要 Lombok 的 `@Data` 注解来生成 getter/setter 等方法。 --- ## ✅ 三、使用 `Environment` 对象读取属性 适用于在任意 Spring Bean 中动态读取配置。 ### 示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class MyEnvironmentComponent { @Autowired private Environment env; public void printAdminSecretKey() { String secretKey = env.getProperty("sky.jwt.admin-secret-key"); System.out.println("Admin Secret Key: " + secretKey); } } ``` ### ✅ 说明: - `Environment` 是 Spring 提供的用于访问环境变量和配置属性的接口。 - 可以读取系统环境变量、JVM 参数、配置文件等。 --- ## ✅ 四、使用 `@PropertySource` 自定义配置文件(非 application.yml) 如果你有自定义的 `.properties` 文件,比如 `myconfig.properties`,可以这样加载: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource("classpath:myconfig.properties") public class MyConfig { @Value("${my.config.key}") private String myKey; // getter / setter } ``` > ⚠️ 注意:`@PropertySource` 不支持 `.yml` 文件,只能用于 `.properties` 文件。 --- ## ✅ 五、读取配置文件中的 List 或 Map(YAML 专属) ### application.yml 示例: ```yaml my: list: - item1 - item2 map: key1: value1 key2: value2 ``` ### Java 类绑定: ```java import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; @Component @ConfigurationProperties(prefix = "my") @Data public class MyCustomProperties { private List<String> list; private Map<String, String> map; } ``` --- ## ✅ 六、通过 `@PostConstruct` 初始化时读取配置 如果你希望在 Bean 初始化阶段读取配置,可以结合 `@PostConstruct`: ```java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyInitComponent { @Value("${sky.jwt.admin-secret-key}") private String adminSecretKey; @PostConstruct public void init() { System.out.println("Admin Secret Key at startup: " + adminSecretKey); } } ``` --- ## ✅ 总结:不同方式适用场景 | 方式 | 适用场景 | 优点 | 缺点 | |------|----------|------|------| | `@Value` | 读取单个属性 | 简单直接 | 不便于管理多个属性 | | `@ConfigurationProperties` | 读取一组配置 | 易于维护、结构清晰 | 需要配合 prefix | | `Environment` | 动态读取属性 | 灵活 | 不适合大量属性绑定 | | `@PropertySource` | 加载自定义 properties 文件 | 可扩展 | 不支持 YAML | | YAML List/Map 映射 | 复杂结构配置 | 强大 | 仅支持 YAML | | `@PostConstruct` | 初始化阶段读取 | 控制执行时机 | 属于生命周期管理 | --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值