標籤:logs strong ica private this lis log tco money
除了第一篇中使用 覆寫的方式進行 自動設定的更改外,還可以通過 Spring Boot 中提供的 application.properties 檔案改變應用的運行時配置。這種配置的方式粒度是非常精細的。
application.properties
在 Spring Boot 應用中,application.properties 檔案在 resource/ 目錄下,初始狀態下,application.properties 是空白的。通過這個檔案可以比較細粒度的控制Spring Boot 中的一些配置,比如 資料庫連結、特定參數配置等。預設情況下,應用啟動後監聽的連接埠為 8080,如果想要將堅挺的連接埠設定為7000,那麼只要在application.properties 檔案中加上 server.port=7000,然後啟動應用,在瀏覽器中 使用 localhost:7000 就可以訪問頁面了。
application.properties 檔案有一些預設的可配置參數,比如spring.datasource.* 可以使用這些配置,對應用中使用的DataSource進行配置。這些已有的配置可以通過文檔查到。使用自主的配置與使用原有配置,方法基本是一致的。舉個例子,如果想在一個類中使用application.properties 中配置的資料。需要使用註解 @ConfigurationProperties(prefix="test")
@Controller@RequestMapping("/")@ConfigurationProperties(prefix = "test")public class ReadingListController { private String property; System.out.println("value" + property); public void setProperty(String property) { this.property=property; }}
在 application.properties 中只要簡單指定 屬性的值:
test.property=just a test
當然,如果想要在代碼中使用 application.properties 中的參數初始化一個類對象,在其他的地方直接以執行個體的方式使用也是非常好的。使用方式與上面基本是一致的。首先在application.properties 檔案中定義需要的資料:
dealer.item=balldealer.fashion=truedealer.money=100dealer.home=shop
定義一個類Dealer,使用當前定義的配置 :
@ConfigurationProperties(prefix = "dealer")
@Configurationpublic class Dealer { private String item; private boolean fashion; private int money; private String home; public String getItem() { return item; } public void setItem(String item) { this.item = item; } public boolean isFashion() { return fashion; } public void setFashion(boolean fashion) { this.fashion = fashion; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public String getHome() { return home; } public void setHome(String home) { this.home = home; }}
Dealer 在Controller 中進行使用:
@Controllerpublic class HelloController { @Autowired private ReaderRepository readerRepository; private Dealer dealer; @Autowired public HelloController(Dealer dealer) { this.dealer = dealer; } @RequestMapping(value = "/prop") public String testProp() { System.out.println("HERE " + dealer.getHome()); return "index"; }}
使用的套路基本上就是這樣的。
Spring Boot . 4 -- 定製 Spring Boot 配置 【2】