首頁 > Java > java教程 > 主體

Spring Boot系列之屬性配置以及自訂屬性配置的具體介紹

黄舟
發布: 2017-07-24 14:16:27
原創
1882 人瀏覽過

在使用spring boot過程中,可以發現專案中只需要極少的配置就能完成對應的功能,這歸功於spring boot中的模組化配置,在pom.xml中依賴的每個Starter都有預設配置,而這些預設配置足以滿足正常的功能開發。

如果需要修改自訂修改預設配置,spring boot 提供了很簡單的方法,只需要在application.properties 中加入修改對應的配置。 (spring boot啟動的時候會讀取application.properties這份預設配置)

一、修改預設配置

例1、spring boot 開發web應用的時候,預設tomcat的啟動端口為8080,如果需要修改預設的端口,則需要在application.properties 添加以下記錄:

server.port=8888
登入後複製
重啟項目,啟動日誌可以看到:Tomcat started on port(s): 8888 (http) 啟動端口為8888,瀏覽器中造訪http://localhost:8888 能正常存取。

例2、spring boot 開發中的資料庫連接資訊配置(這裡使用com.alibaba 的druid), 在application.properties 新增以下記錄:

druid.url=jdbc:mysql://192.168.0.20:3306/test
druid.driver-class=com.mysql.jdbc.Driver
druid.username=root
druid.password=123456
druid.initial-size=1
druid.min-idle=1
druid.max-active=20
druid.test-on-borrow=true
登入後複製

以上兩個例子,說明了如需修改starter模組中的預設配置,只需要在application.properties 新增需要修改的配置即可。

二、自訂屬性配置

在application.properties中除了可以修改預設配置,我們還可以在這配置自訂的屬性,並在實體bean中載入出來。

1、在application.properties中加入自訂屬性配置

com.sam.name=sam
com.sam.age=11
com.sam.desc=magical sam
登入後複製

2、寫Bean類,載入屬性

Sam類別需要新增@Component註解,讓spring在啟動的時候掃描到該類,並添加到spring容器中。

第一種:使用spring支援的@Value()載入

package com.sam.demo.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author sam
 * @since 2017/7/15
 */
@Component
public class Sam {

    //获取application.properties的属性
    @Value("${com.sam.name}")
    private String name;

    @Value("${com.sam.age}")
    private int age;

    @Value("${com.sam.desc}")
    private String desc;
    
    //getter & setter
}
登入後複製

第二種:使用@ConfigurationProperties(prefix="") 設定前綴,屬性上不需要加上註解。

package com.sam.demo.conf;

import org.springframework.stereotype.Component;

/**
 * @author sam
 * @since 2017/7/15
 */
@Component
@ConfigurationProperties(prefix = "com.sam")
public class Sam {

    private String name;

    private int age;

    private String desc;

    //getter & setter
}
登入後複製

3、在controller中註入並使用Sam這個Bean。

package com.sam.demo.controller;

import com.sam.demo.conf.Sam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sam
 * @since 2017/7/14
 */
@RestController
public class IndexController {

    @Autowired
    private Sam sam;

    @RequestMapping("/index")
    public String index() {
        System.out.println(sam.getName() + " " + sam.getAge() + " " + sam.getDesc());
        return "index";
    }

}
登入後複製
瀏覽器存取:http://localhost:8080/index ,控制台正常列印出sam的內容。

三、application.properties 屬性配置詳解

1、參數引用與random隨機數方法的使用

在application.properties內可以直接透過${}引用其他屬性的值,如下:
com.sam.name=sam
com.sam.age=11
com.sam.desc=${name} is ${age} years old.
登入後複製
在application.properties中如果需要取得隨機數,可以透過${random},如下:
#获取随机字符串
com.sam.randomValue=${random.value}

#获取随机字符串:${random.value}
#获取随机int:${random.int}
#获取10以内的随机数:${random.int(10)}
#获取10-20的随机数:${random.int[10,20]}
#获取随机long:${random.long}
#获取随机uuid:${random.uuid}
登入後複製

2、多環境配置

實際開發中可能會有不同的環境,有開發環境、測試環境、生成環境。對於每個環境相關配置都可能有所不同,如:資料庫資訊、連接埠配置、本機路徑配置等。

如果每次切換不同環境都需要修改application.properties,那麼操作是十分繁瑣的。在spring boot中提供了多環境配置,使得我們切換環境變得簡單。

在application.properties同目錄下新建一下三個檔案:

application-dev.properties      //开发环境的配置文件
application-test.properties     //测试环境的配置文件
application-prod.properties     //生产环境的配置文件
登入後複製
上面三個檔案分別對應了開發、測試、生產的設定內容,接下來就是應該怎麼選擇性引用這些配置了。

在application.properties新增:

spring.profiles.active=dev
#引用测试的配置文件
#spring.profiles.active=test
#引用生产的配置文件
#spring.profiles.active=prod
登入後複製
新增spring.profiles.active=dev後啟動應用,會發現引用了dev的這份設定資訊。
可以看出上面三個設定檔符合 application-{profile}.properties 格式,而在application.properties新增的 spring.profiles.active=dev 中的dev正是上面設定檔中的 profile。依具體環境進行切換即刻。

用指令執行jar包啟動應用程式的時候,可以指定對應的設定.

java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
登入後複製

附:設定方式與優先權

这些方式优先级如下:
a. 命令行参数
b. 来自java:comp/env的JNDI属性
c. Java系统属性(System.getProperties())
d. 操作系统环境变量
e. RandomValuePropertySource配置的random.*属性值
f. jar外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
g. jar内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
h. jar外部的application.properties或application.yml(不带spring.profile)配置文件
i. jar内部的application.properties或application.yml(不带spring.profile)配置文件
j. @Configuration注解类上的@PropertySource
k. 通过SpringApplication.setDefaultProperties指定的默认属性
登入後複製

註:命令列參數這種jar套件指定參數啟動應用的方式,可能是不安全的,我們可以設定禁止這種方式啟動應用,如下:

springApplication.setAddCommandLineProperties(false);

package com.sam.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
//        SpringApplication.run(DemoApplication.class, args);
        SpringApplication springApplication = new SpringApplication(DemoApplication.class);
        //禁止命令行设置参数
        springApplication.setAddCommandLineProperties(false);
        springApplication.run(args);
    }
}
登入後複製

補充:

在spring boot 中配置除了支援application.properties,也支援application.yml的設定方式,如下:
新application.yml取代application.properties
server:
  port: 9999

com:
  sam:
    name: sam
    age: 11
    desc: magical sam
登入後複製
注意:port: 9999 中間是有空格的,yml語法請參考:yml設定檔用法

以上是Spring Boot系列之屬性配置以及自訂屬性配置的具體介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!