美文网首页
springboot读取application.yml配置和自定

springboot读取application.yml配置和自定

作者: 缓慢移动的蜗牛 | 来源:发表于2020-03-12 20:41 被阅读0次

    springboot.version==2.2.x.RELEASE

    一、读取application.yml的配置信息

    配置信息如下

    如果application-dev.ymlapplication-prod.yml也有同样的配置,此时系统就会使用spring.profiles.active=xxx指定配置的信息

    person:
      lastName: 张三封${random.uuid} # 或者是 last-name: zhangsan
      age: 21
      boss: false
      birth: 2018/05/15
      maps:  # 或者写成一行{k1: v1,k2: v2}
        k1: v1
        k2: v2
      lists:
        - ${person.lastName}
        - zhangsan
    

    person类

    /**
     * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
     * prefix = "person":配置文件中哪个下面的所有属性进行一一映射
     */
    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
        private String lastName;
        private Integer age;
        private Boolean boss;
    
        private Date birth;
        private Map<String,Object> maps;
        private List<Object> lists;
        
        //getter and setter
    }
    

    测试使用

    直接注入使用即可

    @RestController
    @RequestMapping("/test")
    public class MyTestController {
        @Autowired
        private Person person;
    }
    

    二、读取自定义properties配置文件

    文件位置

    |--resources
       |--config
          |--file-dev.properties
    

    file-dev.properties内容

    txtfile.name=zhangsan
    txtfile.size=123
    

    相应的实体类

    /**
     * @PropertySource:加载指定的配置文件, 只能是properties文件,不能是yml文件
     */
    @Component
    @ConfigurationProperties(prefix = "txtfile")
    @PropertySource("classpath:config/file-${spring.profiles.active}.properties")
    public class FileProperties {
    
        private String name;
    
        private String size;
    
        //getter and setter
    }
    

    测试使用

    直接注入使用即可

    @RestController
    @RequestMapping("/test")
    public class MyTestController {
        @Autowired
        private FileProperties fileProperties;
    }
    

    三、从yml和properties配置文件中读取信息

    相应的实体类

    /**
     * @PropertySource:加载指定的配置文件, 只能是properties文件,不能是yml文件
     */
    @Component
    @ConfigurationProperties(prefix = "person")
    @PropertySource("classpath:config/file-${spring.profiles.active}.properties")
    public class FileProperties {
    
        private String name;
    
        private String size;
    
        @Value("${txtfile.name}")
        private String txFileName;
    
        //getter and setter
    }
    

    相关文章

      网友评论

          本文标题:springboot读取application.yml配置和自定

          本文链接:https://www.haomeiwen.com/subject/giiwjhtx.html