Spring Boot . 4 -- 定製 Spring Boot 配置 【2】

來源:互聯網
上載者:User

標籤: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")
@Configuration
public 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】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.