SpringBoot實戰:SpringBoot之本地配置(一)

Spring程序會按優先級從下面這些路徑來加載application.yml和application.properties配置文件,同時會先加載application.yml文件再加載application.properties配置文件。加載順序優先以下:java

  1. 當前目錄下的/config目錄
  2. 當前目錄
  3. classpath裏的/config目錄
  4. classpath 跟目錄

所以,要外置配置文件就很簡單了,在jar所在目錄新建config文件夾,而後放入配置文件,或者直接放在配置文件在jar目錄git

同時能夠按Profile不一樣環境讀取不一樣配置不一樣環境的配置設置一個配置文件,例如:web

  1. dev環境下的配置配置在application-dev.properties中
  2. test環境下的配置配置在application-test.properties中

在application.properties中指定使用哪個配置文件,spring.profiles.active = dev,能夠經過@value讀取配置值。spring

在resource文件夾下新增config/application-dev.properties,內容以下api

spring.config.test=test

application-dev.properties新增spring.profiles.active = dev配置瀏覽器

#編碼設置
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
spring.http.encoding.enabled=true
spring.messages.encoding=UTF-8

# tomcat 配置
server.tomcat.accept-count=1000
server.tomcat.max-threads=500
# session超時時間,單位是秒
server.servlet.session.timeout=1800

#當前應用http端口
server.port=8787
#訪問地址,該配置能夠不配置,則直接經過ip+port訪問
#server.servlet.context-path=/demo

spring.profiles.active = dev

在使用spring.config.test配置的類中能夠使用@value獲取配置值,@value不能直接注入值給靜態屬性,Spring 不容許/不支持把值注入到靜態變量中Spring支持set方法注入,咱們能夠利用非靜態setter 方法注入靜態變量,而且使用@Value的類必須交個spring進行管理。tomcat

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:54
 * Description :
 */
@RestController
@RequestMapping("/api/demo")
public class HelloWorldController {

    @Value("${spring.config.test}")
    private String test;


    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello world," + test;
    }
}

打開瀏覽器,在地址欄輸入http://127.0.0.1:8787/api/demo/hellosession

至此,SpringBoot簡單讀取本地配置例子演示完畢。app

項目碼雲地址:https://gitee.com/wusycode/spring-boot-wusy-demo.gitspring-boot

相關文章
相關標籤/搜索