注解@Value和@ConfigurationProperties可以用于获取配置文件的属性值,不过有个细节容易被忽略,那就是二者在Spring Boot项目中都是获取默认配置文件的属性值,也就是application.yml或者application.properties的属性值,如果想引用其它配置文件的属性值,就需要使用本篇博文的主角@PropertySource注解。
使用@PropertySource获取对应的properties文件,再用@ConfigurationProperties或者@Value进行属性映射。在application.properties中配置user.properties文件的路径:
config.path= classpath:self/user.properties
user.properties的配置信息如下:
user.id= 1000
user.userName= root
user.msg= true or not
user.age= 1
user.mobilePhone=15190977799
user.address.tel= 0370-97708099
user.address.name=商丘
创建一个Bean,用于展示配置的信息,
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Getter
@Setter
@Component
//方式①
//@PropertySource("classpath:self/user.properties")
//方式②
@PropertySource(value = {"${config.path}"}, encoding= "UTF-8")
@ConfigurationProperties(prefix = "user")
public class User implements Serializable {
//实现serializable接口
private static final long serialVersionUID = -5259637730100548689L;
private Long id;
private String userName;
private String msg;
private Integer age;
private Address address;
private String mobilePhone;
private String remark;
/**
* 无参构造器,服务启动过程中就加载
*/
public User() {
System.out.println("正在初始化 user");
}
public User(Long id, String userName, Integer age) {
this.id = id;
this.userName = userName;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", msg='" + msg + '\'' +
", age=" + age +
", address=" + address +
", mobilePhone='" + mobilePhone + '\'' +
", remark='" + remark + '\'' +
'}';
}
}
如上两种方式都可以配置指定的文件并读取其中的属性。测试用例如下:
@Autowired
private User user;// 不要用 new User()
@PostMapping("/getUser")
public User getUser() {
logger.info("执行结果user = {}", user);
return user;
}
工欲善其事,必先利其器。性能与效率是程序猿永恒的追求,对代码如此,对日常搬砖亦如此。Wiener祝愿各位同仁Work Life Balance,效率高,错误少,回家早...