SpringBoot入門-配置文件

Spring Boot默認從 application.properties 獲取配置,比如我們要配置一個user,首先在 application.properties 中對應 UserProperties 對象字段編寫屬性的 KV 值:

user.name=zhitao
user.age=27
user.sex=man
user.desc=${user.name} is a ${user.sex}

這裏也可以通過佔位符,進行屬性之間的引用。

編寫duiying的UserProperties對象:

@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {
    private  String name;
    private  Integer age;
    private  String sex;
    private  String desc;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
/**getter setter方法省略**/

    @Override
    public String toString() {
        return "UserProperties{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

通過 @ConfigurationProperties(prefix = "user”) 註解,將配置文件中以 user前綴的屬性值自動綁定到對應的字段中。同是用 @Component 作爲 Bean 注入到 Spring 容器中。

如果使用yml文件,則是

## user屬性
user:
  name: zhitao
  age: 27
  sex: man
  desc: ${user.name} is a ${user.sex}${home.city}
這裏會有一個問題:
application.properties 配置中文值的時候,讀取出來的屬性值會出現亂碼問題。原因是,Spring Boot 是以 iso-8859 的編碼方式讀取 application.properties 配置文件,使用 application.yml 則不會出現亂碼問題。


項目結構如圖:


多場景配置問題:

很多場景的配置,比如數據庫配置、Redis 配置、日誌配置等。在不同的環境,我們需要不同的包去運行項目。所以看項目結構,有兩個環境的配置:

Spring Boot 是通過 application.properties 文件中,設置 spring.profiles.active 屬性,比如 ,配置了 dev ,則加載的是 application-dev.properties :


如下:application.properties 的配置是:

spring.profiles.active=test

那麼讀取的就是 application-test.properties 的配置

user.name=taotao
user.age=26
user.sex=man
user.desc=${user.name} is a ${user.sex}

application-dev.properties 的配置爲:

user.name=tao
user.age=28
user.sex=man
user.desc=${user.name} is a ${user.sex}

此時讀取到的用戶名字爲taotao而不是tao。





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