在一些业务需求上,我们需要获取配置文件的某些配置内容,达到某种功能,
那么如何获取spingboot的配置参数内容呢?
最常见的有几种方式
application.yml
    
    1 2 3 4 5 6 7 8
   |  spring:     application:         name: springboot
 
  server:     port: 8080
 
  | 
 方式一:@Value注解
获取少量的配置,可以直接使用@Value注解获取
SpringbootApplicationTests.java
    
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   |  @SpringBootTest class SpringbootApplicationTests {
      @Value("${spring.application.name}")     public String name;
      @Value("${server.port}")     public String port;
      @Test     void contextLoads() {         System.out.println("Application_Name:"+name+"\nPort:"+port);     }
  }
 
  | 
 方式二:Environment接口
SpringbootApplicationTests.java
    
    1 2 3 4 5 6 7 8 9 10 11 12 13
   | @SpringBootTest class SpringbootApplicationTests {
      @Autowired     public Environment env;
      @Test     void contextLoads() {         System.out.println("Application_Name:"+env.getProperty("spring.application.name")                 +"\nPort:"+env.getProperty("server.port"));     }
  }
   | 
 方式三:@ConfigurationProperties注解
    
    1 2 3 4 5 6 7 8 9 10 11 12 13
   |  spring:   application:     name: springboot
  server:   port: 8080
 
  custom:   name: Steve   age: 20
 
 
  | 
 
    
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   |  @Component @ConfigurationProperties(prefix = "custom") @SpringBootTest class SpringbootApplicationTests {
      private String name;
      private String age;
      public String getName() {         return name;     }
      public void setName(String name) {         this.name = name;     }
      public String getAge() {         return age;     }
      public void setAge(String age) {         this.age = age;     }
      @Test     void contextLoads() {         System.out.println("Name:"+getName()+"\nAge:"+getAge());     }
  }
 
  |