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

相关文章
相关标签/搜索