SpingBoot 屬性加載

 

屬性加載順序

配置屬性加載的順序java

  1. 開發者工具 `Devtools` 全局配置參數;
  2. 單元測試上的 `@TestPropertySource` 註解指定的參數;
  3. 單元測試上的 `@SpringBootTest` 註解指定的參數;
  4. 命令行指定的參數,如 `java -jar springboot.jar --name="demo"`;
  5. 命令行中的 `SPRING_APPLICATION_JSONJSON` 指定參數, 如 `java -Dspring.application.json='{"name":"demo"}' -jar springboot.jar`
  6. `ServletConfig` 初始化參數;
  7. `ServletContext` 初始化參數;
  8. JNDI參數(如 `java:comp/env/spring.application.json`);
  9. Java系統參數(`System.getProperties()`);
  10. 操做系統環境變量參數;
  11. `RandomValuePropertySource` 隨機數,僅匹配:`ramdom.*`;
  12. JAR包外面的配置文件參數(`application-{profile}.properties(YAML)`)
  13. JAR包裏面的配置文件參數(`application-{profile}.properties(YAML)`)
  14. JAR包外面的配置文件參數(`application.properties(YAML)`)
  15. JAR包裏面的配置文件參數(`application.properties(YAML)`)
  16. `@Configuration`配置文件上 `@PropertySource` 註解加載的參數
  17. 默認參數(經過 `SpringApplication.setDefaultProperties` 指定)

數字小的優先級越高,即數字小的會覆蓋數字大的參數值。spring

屬性配置方式

 

  1. PropertyPlaceholderConfigurer:

 

    • <context:property-placeholder location="classpath:sys.properties" />
    • @Bean的方式
      @Bean
      public PropertyPlaceholderConfigurer propertiess() {
          PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
          Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")};
          ppc.setLocations(resources);
          ppc.setIgnoreUnresolvablePlaceholders(true);
          return ppc;
      }

       

    • xml 的方式
      <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="locations">
              <list>
                  <value>classpath:sys.properties</value>
              </list>
          </property>
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
      </bean>  

       

  1. 經過 springboot 擴展方式:
    @Bean
    public CommandLineRunner commandLineRunner() {
        return (args) -> {
            System.setProperty("name", "demo");
        };
    }

     

  2. 經過 @PropertySource 配置json

    @PropertySource("classpath:sys.properties")
    @Configuration
    public class DemoConfig {
    }

     

  3. @SpringBootTest(value = { "name=javastack-test", "sex=1" })

 

 

屬性獲取方式

  1. 佔位符:${PlaceHolder}
  2. SpEL 表達式 #{}
  3. 經過 Environment 獲取
    // 只有使用註解 @PropertySource 的時候能夠用,不然會獲得 null。
    @Autowired
    private Environment env;
     
    public String getUrl() {
        return env.getProperty("demo.jdbc.url");
    }  

     

  4. 經過 @Value 注入
    @Value("${demo.jdbc.url}")
    private String url;

     

  5. @ConfigurationProperties
    @Configuration
    @ConfigurationProperties(prefix = "demo.db")
    @Data
    public class DataBase {
        String url;
        String username;
        String password;
    }
相關文章
相關標籤/搜索