Springboot加载自定义yaml文件及复杂类型List/Map使用

springboot的版本:v2.2.1.RELEASE

因为springboot在项目启动的时候是不会自动将自定义(名字不是application*.yml)的配置文件加载到spring容器的,而使用@PropertySource(value = "classpath:test.yml")这样的方式是不能加载.yml文件的。所以我们需要使用另外的方式。

1.将yaml文件加载到spring容器

在springboot启动类(Application.java)中将自定义的yaml文件加载到spring容器

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class YamlApplication {
    public static void main(String[] args) {
        SpringApplication.run(YamlApplication .class, args);
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new         
        PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
	    yaml.setResources(new ClassPathResource("test1.yml"),new ClassPathResource("test2.yml"));
        configurer.setProperties(yaml.getObject());
        return configurer;
    }
}

这样就将自定义的test1.yml和test2.yml加载到了spring容器中。

2.yaml文件实例

具体的yaml文件的用法请参考:YAML 语言教程 - 阮一峰的网络日志

test1.yml

#test1 config
test1:
  test1List:
    - testId: admin
      testName: admin
    - testId: User
      testName: User

test2.yml

#test2 config
test2:
  test2List:
    - testId: User
      apis:
        api1: [get,post]
    - testId: admin
      apis:
        api1: [get,post]
        api2: [get,post]
        api3: [get,put]

3.将yml文件的内容注入到实体Bean

在定义了yaml文件后,我们需要定义与之数据结构相对应的实体bean(实在不知道可以先定义为Object然后调试看映射的数据皆结构,前提是定义的yaml文件的结构是正确的)。

将test1.yml注入到Test1Bean中

package com.springboot.common.beans;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "test1") //指定首节点的名字然后自动匹配注入
public class Test1Bean {
    //test1.yml中test1为第一层节点下面是test1List
    private List<Test1IdBean> test1List;
}

Test1IdBean结构

package com.springboot.common.beans;

import lombok.Data;

@Data
public class Test1IdBean {
    private String testId;

    private String testName;
}

将test2.yml注入到Test2Bean中

package com.springboot.common.beans;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "test2")
public class Test2Bean {
    private List<Test2ApiBean> test2List;
}

Test2ApiBean结构

package com.springboot.common.beans;

import lombok.Data;

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

@Data
public class Test2ApiBean {
    private String testId;
    private Map<String, List<String>> apis;
}

至此已经大功告成,在springboot项目启动的收就会成功的将我们自定义yaml文件加载到spring容器,并自动注入我们定义的实体Bean中去。

4.使用

@Log4j2
@Component
public class SchemaYmlTest {
    @Autowired
    private Test1Bean test1Bean;

    @Autowired
    private Test2Bean test2Bean;

    public void testYml() {
        test1Bean.getTest1List().forEach(a -> System.out.println(a));

        test2Bean.getTest2List().forEach(a -> {System.out.printLn(a.getTestId)})
    }
}

### Spring Boot 中 YML 配置文件的用法及示例 #### 基本概念 `application.yml` 是 Spring Boot 应用程序中最常用的配置文件之一,用于集中管理应用程序的各种设置。该文件采用 YAML (YAML Ain't Markup Language) 格式,具有简洁易读的特点[^1]。 #### 文件结构与语法 YAML 使用缩进来表示层次关系,通常每级缩进两个空格。键值对之间使用冒号分隔,并且支持多行字符串、列表和映射等复杂数据类型[^4]。 #### 示例:基础配置 下面是一个简单的 `application.yml` 文件示例: ```yaml server: port: 8081 spring: datasource: url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC username: root password: secret logging: level: com.example.demo: DEBUG ``` 此段代码设置了服务器端口、数据库连接信息以及日志级别。 #### 多环境配置 为了适应不同运行环境的需求,可以创建多个特定于环境的配置文件,例如 `application-dev.yml`, `application-prod.yml` 等。当指定了活动配置文件时(如通过命令行参数 `-Dspring.profiles.active=dev`),相应的环境配置将会被加载并覆盖默认配置[^3]。 #### 数据类型配置 除了简单属性外,还可以在 `application.yml` 中定义更复杂的 Java 对象或集合类的数据结构。比如 List, Map自定义 Bean 的实例化都可以在这里完成。 ##### 列表(List/Set) ```yaml myapp: features: - featureA - featureB - featureC ``` ##### 映射(Map/Properties) ```yaml myapp: properties: key1: value1 key2: value2 ``` ##### 自定义Bean 假设有一个名为 `MyConfig` 的 POJO 类,则可以在 yaml 文件里这样写: ```java public class MyConfig { private String name; private int age; // getters and setters... } ``` 对应的配置如下所示: ```yaml myconfig: name: John Doe age: 30 ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值