SpringBoot读取配置到对象

本文将介绍如何读取配置文件到List<Object>、Object以及Map<String, Object>中

1 如何读取配置到List<Object>中
1.1 定义配置如下:

test-config:
  list:
    - name: gongmin
      address: 长沙
      phone: 123456789
    - name: xiaoli
      address: 北京
      phone: 987654321

1.2 配置类:

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * TestConfig
 *
 * @author gongmin
 * @date 2023/9/25 14:43
 */
@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix = "test-config")
public class TestConfig {
    private List<UserInfo> list = Collections.emptyList();

    @Getter
    @Setter
    public static class UserInfo {
        private String name;
        private String address;
        private String phone;
    }
}

2 如何读取配置到Map中
2.1 定义配置如下:

test-config:
  map:
    "gongmin": {"name": "gongmin", "address": "长沙", "phone": "123456789"}
    "xiaoli": {"name": "xiaoli", "address": "北京", "phone": "987654321"}

2.2 配置类:

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * TestConfig
 *
 * @author gongmin
 * @date 2023/9/25 14:43
 */
@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix = "test-config")
public class TestConfig {
    private Map<String, UserInfo> map = new HashMap<>(0);

    @Getter
    @Setter
    public static class UserInfo {
        private String name;
        private String address;
        private String phone;
    }
}

3 如何读取配置到Object中
3.1 定义配置如下:

test-config:
  obj:
    name: gongmin
    address: 长沙
    phone: 123456789

3.2 配置类:

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * TestConfig
 *
 * @author gongmin
 * @date 2023/9/25 14:43
 */
@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix = "test-config")
public class TestConfig {
    private UserInfo obj = new UserInfo();

    @Getter
    @Setter
    public static class UserInfo {
        private String name;
        private String address;
        private String phone;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容