(三) Spring Boot讀取配置檔案中的資料

2021-09-24 11:17:44 字數 2237 閱讀 5567

book.name = springcloudinaction

book.author = hdn

1、通過@value註解進行讀取1.1、配置乙個bean使其裝載到spring的ioc容器中

/**

* @author hdn

* @date 2019/6/14 14:37

*/@component

public class book ")

private string name;

@value("$")

private string author;

public string getname()

public void setname(string name)

public string getauthor()

public void setauthor(string author)

}

1.2、通過注入book來獲取配置檔案中的值

/**

* @author hdn

* @date 2019/6/5 16:19

*/@restcontroller

public class hellocontroller

}

1.3、執行結果如下:

2、通過注入environment物件來讀取配置檔案的內容

2.1、直接注入environment物件根據getproperty(param)方法就可得到對應的值

param:配置檔案中=前面的屬性(key屬性)

/**

* @author hdn

* @date 2019/6/5 16:19

*/@restcontroller

public class hellocontroller

}

2.2、執行結果如下:

這裡需要注意environment導的包:import org.springframework.core.env.environment;

3、通過@configurationproperties來讀取配置檔案的內容

3.1、配置乙個bean使其裝載到spring的ioc容器中

/**

* @author hdn

* @date 2019/6/14 15:25

*/@component

@configurationproperties(prefix = "book")

public class bookconfigpro

public void setname(string name)

public string getauthor()

public void setauthor(string author)

}

3.2、通過注入bookconfigpro來獲取配置檔案中的值

/**

* @author hdn

* @date 2019/6/5 16:19

*/@restcontroller

public class hellocontroller

@autowired

book book;

@autowired

environment env;

@autowired

bookconfigpro bookconfigpro;

public string getproperties()

}

3.3、執行結果如下:

二、如果有自己定義的配置檔案,如config.properties,要使用@propertysource(value="config.properties")註解來載入自定義配置檔案中的內容。

spring boot 配置檔案讀取

如圖所示,可以重新賦值予以覆蓋。mail setting 設定郵箱主機 email.host smtp.163.com email.port 25 設定使用者名稱 email.from xx xx.com 設定密碼 email.frompassword 設定是否需要認證,如果為true,那麼使用者名...

springBoot讀取配置檔案

1.讀核心配置檔案 2.讀自定義配置檔案 建立乙個配置檔案對應的實體類新增如下註解 configuration propertysource value classpath mail.properties configurationproperties prefix mail locations c...

springboot讀取配置檔案

核心配置檔案和自定義配置檔案。核心配置檔案是指在resources根目錄下的application.properties或application.yml配置檔案。為了不破壞核心檔案的原生態,但又需要有自定義的配置資訊存在,一般情況下會選擇自定義配置檔案來放這些自定義資訊,這裡在resources c...