Spring Boot 可以加载一些位于项目外部的配置文件。我们可以通过如下 2 个参数,指定外部配置文件的路径:
spring.config.location
spring.config.additional-location

spring.config.location:这个会使项目原本的配置文件失效。
spring.config.additional-location:不会使项目内置的配置文件失效,两者会互补,additional-location配置的文件优先级更高。

验证

准备

1、新建一个Spring Boot项目
2、写一个Controller来测验我们的结果

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorld {

	@RequestMapping("hello")
	public String hello(){
		return "hello";
	}
}

3、添加application.properties配置为

server.port=8080
server.servlet.context-path=/inner

4、启动,访问http://localhost:8080/inner/hello
注意:我么这里是使用端口号为8080,项目路径inner
在这里插入图片描述

验证 spring.config.location

1、将准备好的项目通过maven打包,生成.jar文件
在这里插入图片描述
2、在这个目录下新建一个application.properties文件,配置为

server.port=8081

3、命令行打开运行

java -jar  demo-0.0.1-SNAPSHOT.jar --spring.config.location=application.properties

4、结果

  • 可以看出访问 http://localhost:8080/inner/hello 出错
    在这里插入图片描述
  • 访问 http://localhost:8081/hello 成功
    在这里插入图片描述

验证 spring.config.additional-location

前两个步骤与上述验证一致
第三个步骤修改为

java -jar  demo-0.0.1-SNAPSHOT.jar --spring.config.additional-location=application.properties

结果
访问 http://localhost:8080/inner/hello 出错
在这里插入图片描述
访问 http://localhost:8081/inner/hello 成功
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐