Spring程序会按优先级从下面这些路径来加载application.yml和application.properties配置文件,同时会先加载application.yml文件再加载application.properties配置文件。加载顺序优先以下:java
所以,要外置配置文件就很简单了,在jar所在目录新建config文件夹,而后放入配置文件,或者直接放在配置文件在jar目录。git
同时能够按Profile不一样环境读取不一样配置,不一样环境的配置设置一个配置文件,例如:web
在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