SpringBoot @ConfigurationProperties 注解使用

@ConfigurationProperties 用于将配置文件(如 application.properties 或 application.yml)中的属性批量绑定到一个 Java Bean 中。

1. 定义配置文件

在 application.properties 或 application.yml 中定义一组具有相同前缀的属性。

application.yml :

yaml 复制代码
person:
  id: 1
  name: tom
  hobby:
    - play
    - read
    - sleep
  family:
    - father
    - mother
  map:
    k1: v1
    k2: v2
  pet:
    type: dog
    name: kity

application.properties :

yaml 复制代码
person.id=1
person.name=tom
person.hobby=play,read,sleep
person.family=father,mother
person.map.k1=v1
person.map.k2=v2
person.pet.type=dog
person.pet.name=kity

2. 创建配置类

创建一个 Java Bean,并使用 @ConfigurationProperties 注解将配置文件中的属性绑定到该 Bean 中。

Person.java

java 复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component    // 用于将Person类作为Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以person开头的属性注入到该类中
public class Person {
    private int id;            //id
    private String name;      //名称
    private List hobby;       //爱好
    private String[] family; //家庭成员
    private Map map;
    private Pet pet;          //宠物

  //省略getter,setter,toString
}

Pet.java

java 复制代码
public class Pet {
    private String type;
    private String name;

    //省略getter,setter,toString
}

3. 测试方法

java 复制代码
@SpringBootTest
public class WebTest {

    @Autowired
    private Person person;
    
    @Test
    public void test(){
        System.out.println(person);
    }

}

4. 运行并测试

相关推荐
千寻技术帮6 小时前
微信小程序+Spring Boot 烘焙商城系统(附完整源码+数据库+部署文档)50053
数据库·spring boot·微信小程序·烘焙商城
CoderYanger9 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
她的男孩10 小时前
状态默认填了 DRAFT,同步后却变成 '''DRAFT'':Forge Admin 清洗 PG 的 COLUMN_DEFAULT
spring boot·低代码·postgresql
考虑考虑1 天前
记一次@Async生产事故
spring boot·后端·spring
小荷才露尖尖角,早有蜻蜓立上头1 天前
SpringBoot 定时任务
java·spring boot·后端
码云社区1 天前
Spring Boot上门按摩服务系统源码:上门到店服务目录与门店协同方案
java·spring boot·后端·上门服务·上门按摩·上门小程序
她的男孩1 天前
会签选了两个人,待办却生成一条谁也办不了:Forge Admin 按人拆开自选审批人
spring boot·低代码·工作流引擎
头发还在的女程序员1 天前
Spring Boot云快充协议接入:Netty报文分帧、长度检查与校验处理设计
java·spring boot·后端·充电桩·充电桩小程序·云快充
captain3761 天前
SpringCloud(12)-Gateway
spring boot·spring cloud·gateway
جيون داد ناالام ميづ1 天前
三、MyBatis 与 Spring Boot 集成:极简配置 + 分页 / 乐观锁实战
spring boot·后端·mybatis