springboot uses the PropertyResource annotation to read the properties of the specified configuration file (podcast code)

Posted by Nimbuz on Mon, 06 Apr 2020 19:01:17 +0200

Chapter one: SpringBoot/Spring uses @ Value for attribute binding (podcast code for wisdom spreading)

 

The ConfigurationProperties annotation will read the properties from the global configuration file by default. When there are many properties, the main configuration file(
application.yml, application.properties) will be bloated, so it is necessary to configure a certain type of property separately

@PropertyResource reads the specified configuration file
The value of the annotation supports string array and can fill in multiple configuration file paths, such as
@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;
}

Configuration file person.properties

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

test case

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);
    }
}

Result:

Topics: Java Lombok Junit SpringBoot