1. 程式人生 > 其它 >SpringBoot 配置繫結

SpringBoot 配置繫結

技術標籤:SpringBoot

一、如何使用Java讀取到properties檔案中的內容,並且把它封裝到JavaBean中,以供隨時使用

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
Enumeration enum1 = pps.propertyNames();//得到配置檔案的名字 while(enum1.hasMoreElements()) { String strKey = (String) enum1.nextElement(); String strValue = pps.getProperty(strKey); System.out.println(strKey + "=" + strValue); //封裝到JavaBean。
} } }
  1. @Component + @ConfigurationProperties(即容器中的元件,標記 @ConfigurationProperties即可繫結)
  • properties檔案:
  • 在這裡插入圖片描述
/**
 * 只有在容器中的元件,才會擁有SpringBoot提供的強大功能
 */
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;
    private Integer price;

    public
String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", price=" + price + '}'; } }
  1. @EnableConfigurationProperties + @ConfigurationProperties
@EnableConfigurationProperties(Car.class)
// @EnableConfigurationProperties的功能如下:
//1、開啟Car配置繫結功能
//2、把這個Car這個元件自動註冊到容器中
public class MyConfig {
}

以後就可以隨心所欲地給javabean繫結資料