本文主要是介绍SpringBoot@PropertySource注解的用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.@Value和@ConfigurationProperties都可以用于获取配置文件的属性值,不过有个细节容易被忽略,那就是,这两个注解在Springboot项目中都是获取默认配置文件的属性值,也就是application.yml或者application.properties的属性值
如果想引用其它配置文件的属性值,就可以使用本博客介绍的@PropertySource注解
新建一个user.properties的配置文件:
user.userName= root
user.isAdmin= true
user.regTime= 2019/11/01
user.isOnline= 1
user.maps.k1=v1
user.maps.k2=v2
user.lists=list1,list2
user.address.tel= 15899988899
user.address.name=上海
使用@PropertySource(“classpath:user.properties”)获取对应的properties文件,再用@ConfigurationProperties(prefix = “user”)进行属性映射
package org.muses.jeeplatform.bean;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.List;
import java.util.Map;@Component
@PropertySource("classpath:user.properties")
@ConfigurationProperties(prefix = "user")
public class User {private String userName;private boolean isAdmin;private Date regTime;private Long isOnline;private Map<String,Object> maps;private List<Object> lists;private Address address;@Overridepublic String toString() {return "User{" +"userName='" + userName + '\'' +", isAdmin=" + isAdmin +", regTime=" + regTime +", isOnline=" + isOnline +", maps=" + maps +", lists=" + lists +", address=" + address +'}';}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public boolean isAdmin() {return isAdmin;}public void setAdmin(boolean admin) {isAdmin = admin;}public Date getRegTime() {return regTime;}public void setRegTime(Date regTime) {this.regTime = regTime;}public Long getIsOnline() {return isOnline;}public void setIsOnline(Long isOnline) {this.isOnline = isOnline;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}
}
注意:对于@PropertySource注解,默认是不支持yml配置文件读取的,需要修改重写才可以
这篇关于SpringBoot@PropertySource注解的用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!