yml封装map或对象

  • 目录结构

在这里插入图片描述

  • application.yml

    server:
      port: 8081
    
    # 引入其他的配置文件
    spring:
      profiles:
        include:
          - dict1
          - dict2
    
  • application-dict1.yml

    test01:
      var01:
        username: zhangsan
        age: 20
      var02: this is string
    
  • cn.king.demo01.properties.Demo01Properties

    package cn.king.demo01.properties;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    import java.util.Map;
    
    /**
     * @author: wjl@king.cn
     * @time: 2020/11/23 22:45
     * @version: 1.0.0
     * @description: yml封装map或者对象
     */
    
    // 必须有getter/setter
    @Data
    // 必须加@Component
    @Component
    // 指定引用哪个配置文件中的数据. 我们在application.yml中使用了spring.profiles.include后下面的注解可以不写
    @PropertySource(value = {"classpath:application-dict1.yml"}, encoding = "UTF-8")
    @ConfigurationProperties(prefix = "test01")
    public class Demo01Properties {
    
        // 注意, 封装对象不能使用@Value
        // 注意, 成员变量名要和配置文件中配置的参数名一致
        private Map<String, String> var01;
    
        private String var02;
    
    }
    
  • cn.king.demo01.Demo01ApplicationTests

    package cn.king.demo01;
    
    import cn.king.demo01.properties.Demo01Properties;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.jupiter.api.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import javax.annotation.Resource;
    
    @Slf4j
    @SpringBootTest
    class Demo01ApplicationTests {
    
        @Resource
        private Demo01Properties demo01Properties;
    
        @Test
        void test01() {
            demo01Properties.getVar01().forEach((k, v) -> log.info(k + "--" + v));
            log.info("--------------");
            log.info(demo01Properties.getVar02());
        }
    
    }
    
  • pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值