springboot2實戰四-配置文件詳解- @ConfigurationProperties

配置文件相關-

1、@ConfigurationProperties(prefix = “hpf”)

1.定義yml/properties文件

hpf:
  name: zhangsan
  age: 12

​ 2.定義映射類

@Component
@ConfigurationProperties(prefix = "hpf")
public class User {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

注意:默認從全局配置文件中獲取值

2、@Value使用

/**
 * @author hanpengfei1
 * @date 2020/3/13  21:40
 */
@Component
//@ConfigurationProperties(prefix = "hpf")
public class User {

    @Value("${hpf.name}")
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

注意:默認從全局配置文件中獲取值,以上方式均能講配置文件中的屬性值映射到bean中。

3、@PropertySource&ImportResource

@PropertySource(value={"classpath:person.properties"}) //從指定屬性文件中讀取屬性
@ImportResource(locations = {"calsspath:beans.xml"}) //導入spring的配置文件,讓配置文件裏的內容生效;springboot裏面沒有配置文件,我們自己的配置文件也不能自動識別,需要此註解導入

resources/beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <bean id="helloService" class="com.hpf.study.springbootdemo.service.HelloService"></bean>
</beans>

resources/person.properties

person.name=lisi
person.age=121

4、springboot推薦給容器中添加組件的方式

  1. 配置類@Configuration ====相當於之前的spring配置文件

  2. @Bean

    /**
     * @author hanpengfei1
     * @date 2020/3/13  22:53
     */
    @Configuration    // 指明當前是一個配置類,相當於之前的配置文件。
    public class MyAppConfig {
        @Bean
        public HelloService helloService(){//用方法名作爲 bean id
            return new HelloService();
        }
    }
    

5、配置文件加載位置

springboot 啓動會掃描以下位置的application.properties或application.yml文件作爲spring boot的默認配置文件

  • file:./config/

  • file:./

  • classpath:./config/

  • classpath:./

    以上按照優先級從高到低的順序,所有位置的文件都會被加載,高優先級配置會覆蓋低優先級配置內容

    也可以通過配置spring.config.location來改變默認配置

6、外部配置加載順序

優先級從高到底,高優先級配置覆蓋低優先級配置

  1. 命令行參數

  2. 來自java:comp/env屬性

  3. Java系統屬性(system.getProperties)

  4. 操作系統環境變量

  5. RandomValuePropertySource配置的random.*屬性值

  6. jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件

  7. jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件

  8. jar包外部的application.properties或application.yml

  9. jar包內部的application.properties或application.yml

  10. @Configuration註解類上的@PropertySource

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章