1.添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
功能
@PropertySource加载指定的属性文件(*.properties)到 Spring 的 Environment 中。可以配合 @Value 和@ConfigurationProperties 使用。
@PropertySource 和 @Value
组合使用,可以将自定义属性文件中的属性变量值注入到当前类的使用@Value注解的成员变量中。
@PropertySource 和 @ConfigurationProperties
组合使用,可以将属性文件与一个Java类绑定,将属性文件中的变量值注入到该Java类的成员变量中。
属性文件:demo.properties
demo.name=huang
demo.sex=1
demo.type=demo
示例一:@PropertySource + @Value
package com.huang.pims.demo.props;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = {"demo/props/demo.properties"})
public class ReadByPropertySourceAndValue {
@Value("${demo.name}")
private String name;
@Value("${demo.sex}")
private int sex;
@Value("${demo.type}")
private String type;
@Override
public String toString() {
return "ReadByPropertySourceAndValue{" +
"name='" + name + '\'' +
", sex=" + sex +
", type='" + type + '\'' +
'}';
}
}
示例二:@PropertySource 和 @ConfigurationProperties
package com.huang.pims.demo.props;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = {"demo/props/demo.properties"})
@ConfigurationProperties(prefix = "demo")
public class ReadByPropertySourceAndConfProperties {
private String name;
private int sex;
private String type;
public void setName(String name) {
this.name = name;
}
public void setSex(int sex) {
this.sex = sex;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public int getSex() {
return sex;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "ReadByPropertySourceAndConfProperties{" +
"name='" + name + '\'' +
", sex=" + sex +
", type='" + type + '\'' +
'}';
}
}
@ConfigurationProperties注解,prefix表示读取的配置信息的前缀,只写前缀,默认读取application.yml中数据。重点!!一定要在这个类中写getter和setter,否则配置中的属性值无法自动注入