前言web
===========================================spring
初步接觸Spring Bootspringboot
===========================================app
資源文件中自定義屬性值,配置在一個對象bean上,而後在程序中可使用bean的屬性值。ide
一。this
二。spa
@Component
標誌本類爲一個bean
@PropertySource(value = "classpath:/application.properties")
指定綁定哪一個資源文件,【若是要綁定自定義的資源文件中的值的話,是能夠用上的】這裏的application.properties文件是springboot默認的資源文件,是能夠不用指定的,這裏綁定的話,會去加載綁定兩次。
@ConfigurationProperties(prefix = "com.sxd")
指定綁定資源文件中前綴以com.sxd開頭的屬性名,其餘的不會綁定過來。由於這裏location屬性取消了,因此採用上面註解進行替代方案
package com.sxd.beans; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @PropertySource(value = "classpath:/application.properties") @ConfigurationProperties(prefix = "com.sxd") public class ConfigBean { private String name; private String want; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWant() { return want; } public void setWant(String want) { this.want = want; } }
三。code
@EnableConfigurationProperties(ConfigBean.class)
激活綁定的bean
@Autowired
將綁定的某個bean自動注入
package com.sxd.firstdemo; import com.sxd.beans.ConfigBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication @EnableConfigurationProperties(ConfigBean.class) public class FirstdemoApplication { @Autowired ConfigBean configBean; @RequestMapping("/") public String index(){ return "Hello Spring Boot,"+configBean.getName(); } public static void main(String[] args) { SpringApplication.run(FirstdemoApplication.class, args); } }
四。對象
運行結果:blog