本身定義一個配置文件test.propertiesjava
my.name=xuhaixing my.age=25 my.sex=man
@Configuration //證實這是一個配置類 @PropertySource(value = {"classpath:test.properties"}, ignoreResourceNotFound = true)//能夠放多個,{}裏面用,分開 public class User { //能夠不用set方法,直接就能注入,屬於注入 @Value("${my.name}") private String name; @Value("${my.age}") private int age; @Value("${my.sex}") private String sex; public String getName() { return name; } public int getAge() { return age; } public String getSex() { return sex; } }
注意:使用@value註解所在的類必須是一個IOC容器中的對象,即便用@Configuration、@Component等註解注入到容器的對象。spring
其中@PropertySource指明要加載的配置文件,若是沒有用該註解指明,默認讀取的springboot的全局配置文件,即:application.properties或application.ymljson
能夠在controller中把user類注入,而後測試一下:springboot
@RestController public class HelloController { @Autowired private User user; @RequestMapping(value = "/getUser") public String getUser() { return user.getName() + " " + user.getSex() + " " + user.getAge(); } }
注意:省略了springboot的pom文件以及啓動類app
@Configuration @PropertySource(value = "classpath:test.properties") @ConfigurationProperties(prefix = "my") //須要有set方法,prefix指明該對象中全部屬性的前綴,對應文件中的屬性名 public class UserPrefix { private String name; private int age; private String sex; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setSex(String sex) { this.sex = sex; } public String getName() { return name; } public int getAge() { return age; } public String getSex() { return sex; } }
而後注入到controller中,測試測試
@RestController @EnableConfigurationProperties({UserPrefix.class}) //激活配置,測試了一下,也能夠沒有 public class HelloPrefixController { @Autowired private UserPrefix userPrefix; @RequestMapping(value = "/getUserPrefix") public String getUserPrefix() { return userPrefix.getName() + " " + userPrefix.getSex() + " " + userPrefix.getAge(); } }
注意:兩種讓@ConfigurationProperties生效的方法:this
一、在這裏@ConfigurationProperties所註解的類,添加了@Configuration註解,表示該類UserPrefix會注入到IOC容器中做爲bean,因此@ConfigurationProperties註解就能夠自動生效,自動全量注入該對象的自定義屬性。其實把@Configuration替換成@Component等任何一個能夠實現注入IOC容器的註解均可以使@ConfigurationProperties生效;url
二、若是@ConfigurationProperties所註解的類沒有添加註解注入到IOC容器中,則必須在使用的地方添加@EnableConfigurationProperties註解並指明須要注入到容器的類,來注入到容器中,從而使@ConfigurationProperties生效;spa
結論:這裏用了@Configuration註解,因此能夠去掉@EnableConfigurationProperties({UserPrefix.class}) ,測試沒問題。.net
@ ConfigurationProperties |
@ Value | |
---|---|---|
功能 | 批量注入 | 單個注入 |
鬆散綁定(鬆散語法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
複雜類型封裝 | 支持 | 不支持 |
person.fullName 與類中同名 person.full-name 使用 - 替換大寫 person.full_name 使用 _ 替換大寫
@Value 不支持 鬆散綁定,配置文件名必須和類屬性名相同。不然則會報錯:
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person.fullNname' in value "${person.fullNname}"
@Value("#{11*2}") private Integer age;
@Data @Component @ConfigurationProperties(prefix = "person") @Validated //JSR303數據校驗 public class Person { @NotNull //不能爲空 private String name; @Email // 必須爲Email 格式 private String fullName; private Integer age; private List<String> list; private Map<String,String> map; private Dog dog; }
person: name: xiaoming full-name: 小明 age : 11 list: -a -b -c -d map: {key1: value1,key2: value2} dog: name: tom age: 3
此時full-name並非一個Email 格式內容,啓動項目報錯:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'person' to com.example.demo.entity.Person failed: Property: person.fullName Value: 小明 Origin: class path resource [application.yml]:9:14 Reason: 不是一個合法的電子郵件地址
@Value 並不支持讀取複雜類型的配置項。
@ConfigurationProperties處理複雜類型的例子以下:
屬性文件以下:
com.zyd.type3=Springboot - @ConfigurationProperties com.zyd.title3=使用@ConfigurationProperties獲取配置文件 #map com.zyd.login[username]=zhangdeshuai com.zyd.login[password]=zhenshuai com.zyd.login[callback]=http://www.flyat.cc #list com.zyd.urls[0]=http://ztool.cc com.zyd.urls[1]=http://ztool.cc/format/js com.zyd.urls[2]=http://ztool.cc/str2image com.zyd.urls[3]=http://ztool.cc/json2Entity com.zyd.urls[4]=http://ztool.cc/ua
@Component @ConfigurationProperties(prefix = "com.zyd") public class PropertiesConfig { public String type3; public String title3; public Map<String, String> login = new HashMap<String, String>(); public List<String> urls = new ArrayList<>(); public String getType3() { return type3; } public void setType3(String type3) { this.type3 = type3; } public String getTitle3() { try { return new String(title3.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return title3; } public void setTitle3(String title3) { this.title3 = title3; } public Map<String, String> getLogin() { return login; } public void setLogin(Map<String, String> login) { this.login = login; } public List<String> getUrls() { return urls; } public void setUrls(List<String> urls) { this.urls = urls; } }
啓動類:
@SpringBootApplication @RestController public class Applaction { @Autowired private PropertiesConfig propertiesConfig; @RequestMapping("/config") public Map<String, Object> configurationProperties() { Map<String, Object> map = new HashMap<String, Object>(); map.put("type", propertiesConfig.getType3()); map.put("title", propertiesConfig.getTitle3()); map.put("login", propertiesConfig.getLogin()); map.put("urls", propertiesConfig.getUrls()); return map; } public static void main(String[] args) throws Exception { SpringApplication application = new SpringApplication(Applaction.class); application.run(args); } }
轉載:https://blog.csdn.net/u012326462/article/details/80686462