SpringBoot2-配置繫結
阿新 • • 發佈:2022-03-06
當我們使用傳統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。 } } }
在SpringBoot2我們需要進行此操作時,只需要使用@ConfigurationProperties即可
假設有配置檔案application.properties
mycar.brand=BYD
mycar.price=100000
只有在容器中的元件,才會擁有SpringBoot提供的強大功能
@Component @ConfigurationProperties(prefix = "mycar") public class Car { ... }
Spring Boot另一種配置配置繫結:
@EnableConfigurationProperties + @ConfigurationProperties
1. 開啟Car配置繫結功能
2. 把這個Car這個元件自動註冊到容器中
@EnableConfigurationProperties(Car.class) public class MyConfig { ... }
@ConfigurationProperties(prefix = "mycar") public class Car { ... }