美文网首页SpringBoot专题
SpringBoot读取配置文件

SpringBoot读取配置文件

作者: 蔚蓝的海洋 | 来源:发表于2021-11-07 13:46 被阅读0次

    Component+ConfigurationProperties

    个人推荐使用方法

    • 配置文件

      # application.properties
      mycar.brand=BYD
      mycar.price=50000
      
      # or application.yml
      mycar:
        brand: BYD
        price: 50000
      
    • Car.java

      /**
       * @Author blue-ocean
       * @Description //@ConfigurationProperties将配置文件映射为Java Bean键值对类
       * @Date 2021/11/6
       **/
      
      @Data
      @Component
      @ConfigurationProperties(prefix = Car.PREFIX)
      public class Car {
      
          public static final String PREFIX = "mycar";
      
          private String brand;
          private Integer price;
      }
      
    • CarController.java

      @RestController
      public class CarController {
      
          @Autowired
          Car car;
      
          @RequestMapping("/car")
          public Car car(){
              return car;
          }
          
      }
      

    EnableConfigurationProperties

    引用别人的bean文件时常用方法,加在配置类上

    @EnableConfigurationProperties 文档中解释:
    @EnableConfigurationProperties注解应用到你的@Configuration时, 任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。 这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。

    如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties的类进行了一次注入。

    相关文章

      网友评论

        本文标题:SpringBoot读取配置文件

        本文链接:https://www.haomeiwen.com/subject/cfdezltx.html