Springboot 读取 properties 并与实体类进行绑定

Springboot 使用 @ConfigurationProperties 和 @PropertySource 来读取指定位置的 .peoperties 配置文件,并将配置文件中的 value 值与对应的实体类进行绑定,具体步骤如下:

1、配置文件

// 基本数据类型的值与实体类中属性进行映射绑定
person.name=小毛毛
person.age=21
person.height=157.00
// 数组元素与实体类中 hobby 属性进行映射绑定
person.hobby[0]=LOL
person.hobby[1]=KFC
person.hobby[2]=COFFE
// List集合中元素与实体类 pets 属性进行映射绑定
person.pets[0].name=Husky
person.pets[0].age=2
person.pets[0].color=gray
person.pets[1].name=persian
person.pets[1].age=3
person.pets[1].color=orange
// Map集合中元素与实体类中 featureLevel 属性进行映射绑定
person.featureLevel.clever=10
person.featureLevel.lovely=8
person.featureLevel.funny=8

2、实体类 Person

// 将 Person 注入到 IOC 容器中,只有容器中的组件才能使用 Springboot 的强大功能
@Configuration
// 将 person 下级的 key 与实体类进行映射绑定,并为其注入属性值
@ConfigurationProperties(prefix = "person")
// 加载指定位置的 properties 配置文件
@PropertySource("classpath:config/application.properties")
// 该类省略了 set/get 方法
public class Person {
    // 基本数据类型的属性
    private String name;
    private Integer age;
    private double height;
    // 数组
    private String[] hobby;
    // List 集合
    private List<Pet> pets;
    // Map 集合
    private Map<String, String> featureLevel;
}

3、实体类 Pet (省略 get/set/toString)

public class Pet {
    private String name;
    private String age;
    private String color;
}

4、测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot01ApplicationTests {
    @Autowired
    private ApplicationContext ioc;

    @Test
    public void testProperties() {
        Person person = ioc.getBean("person", Person.class);
        System.out.println(person);
    }
}

5、测试结果

Person{
	name='小毛毛', 
	age=21, 
	height=157.0, 
	hobby=[LOL, KFC, COFFE], 
	pets=[
		Pet{name='Husky', age='2', color='gray'}, 
		Pet{name='persian', age='3', color='orange'}
		], 
	featureLevel={clever=10, lovely=8, funny=8}
}

  

原文地址:https://www.cnblogs.com/xiaomaomao/p/12074442.html