SpringBoot2-配置绑定

当我们使用传统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 {
...
}

 

posted @ 2022-03-06 16:34  Soleili  阅读(48)  评论(0编辑  收藏  举报