一、@PropertySource
@PropertySource:加载指定的配置文件,只使用于.properties格式的文件;
@ConfigurationProperties默认是从全局配置文件中获取值的,如果把所有的配置都写在全局配置文件中,就会显得主配置文件内容特别多。所以我们把一些和Spring Boot无关的配置单独放在一个配置文件下,这个时候就需要@PropertySource;
@PropertySource需要与@ConfigurationProperties或则@Value配合使用;
主配置文件application.yml或则application.properties优先级高于@PropertySource指定的配置文件;
- 将主配置文件application中person属性注释掉,如果不注释掉,主配置文件中的内容会覆盖掉指定配置文件中的内容;
- resource文件夹下新建指定配置文件person.properties
person.last-name=王五
person.age=25
person.boss=true
person.birth=201901/01/05
person.maps.k1=v51
person.maps.k2=v52
person.maps.k3=v53
person.lists=aa,bb,cc
person.dog.name=五花狗
person.dog.age=5
- Person类上添加@PropertySource
package cn.springboottest.springboot.bean;
import org.springframework.beans.factory.annotation.Value;
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;
/**
* 将配置文件中配置的每一个属性值,映射到这个组件中
* @ConfigurationProperties: 告诉Spring Boot将本类中的所有属性和配置文件中相关的配置进行绑定
* prefix ="person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能
*
* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
*
*
*/
@PropertySource(value = {
"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
/*
<bean class="cn.springboottest.springboot.bean.Person" >
<property key="lastName" value="字面量/${key}从环境变量,配置文件中获取值/#{SpEL}"></property>
</bean>
*/
//@Value("${person.last-name}")
// @Email
private String lastName;
//@Value("#{11*5}")
private Integer age;
//@Value("true")
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName