zoukankan      html  css  js  c++  java
  • springboot使用PropertyResource注解读取指定配置文件的属性(尚硅谷)

    接上篇:SpringBoot/Spring使用@Value进行属性绑定(传智播客代码)

    ConfigurationProperties注解默认会从全局配置文件读取属性,当属性多的时候,主配置文件(
    application.yml、application.properties)会臃肿,因此有必要把某一类别属性单独分开配置

    @PropertyResource读取指定配置文件
    该注解的value支持string数组,可以填写多个配置文件路径,例如
    @PropertyResource(value={"aaa.properties","classpath:bbb.properties"})

    Person.java
    package com.atguigu.bean;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    import org.springframework.validation.annotation.Validated;
    
    import javax.validation.constraints.Email;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Component
    @PropertySource(value = {"classpath:person.properties"})
    @ConfigurationProperties(prefix = "person")
    @Validated
    public class Person {
    
        private String lastName;
        private Integer age;
        private Boolean boss;
        private Date birth;
    
        private Map<String,Object> maps;
        private List<Object> lists;
        private Dog dog;
    }

    配置文件person.properties

    person.lastName=李四
    person.age=18
    person.boss=false
    person.birth=2017/12/12
    person.maps.k1=v1
    person.maps.k2='zhangsan 
    lisi'
    person.maps.k3="zhangsan 
    lisi"
    person.lists=[lisi, zhaoliu]
    person.dog.name=happy
    person.dog.age=5

    测试用例

    package com.atguigu;
    
    import com.atguigu.bean.Person;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Slf4j
    class DemoApplicationTests {
    
        @Autowired
        Person person;
        
        @Test
        void customPropertiesTest()
        {
            log.info("{}",person);
        }
    }

    结果:

    
    
  • 相关阅读:
    未让换行符弄错了数据
    REPLICATE
    内存 商业智能
    sql
    PageMethods介绍
    在ASP.NET AJAX中如何判断浏览器及计算其宽高
    用JavaScript实现网页图片等比例缩放
    js技巧收集(200多个)(转自:asp.net中文俱乐部)
    C#调用ORACLE存储过程返回结果集及函数
    Using PageMethods to access Session data
  • 原文地址:https://www.cnblogs.com/passedbylove/p/12639226.html
Copyright © 2011-2022 走看看