springBoot传参解析

springBoot分为好几个环境,开发和测试,生产肯定不一样,一般来说都是通过命令行传参确定使用那个profile

springBootLogo

先复制粘贴一下文档,看看springBoot传参的优先级吧

  1. Default properties (specified by setting SpringApplication.setDefaultProperties).
  2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
  3. Config data (such as application.properties files).
  4. A RandomValuePropertySource that has properties only in random.*.
  5. OS environment variables.
  6. Java System properties (System.getProperties()).
  7. JNDI attributes from java:comp/env.
  8. ServletContext init parameters.
  9. ServletConfig init parameters.
  10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
  11. Command line arguments.
  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
  13. @TestPropertySource annotations on your tests.
  14. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

14个优先级,看起来非常多,比较复杂,而且存在优先级,那就意味着,都是根据优先级覆盖的,可能你明明没配,但是优先级低的配了,你必须要覆盖才能修改

虽然优先级很多,但是实际使用的时候,注意一下即可,给你那么多选择,你可以不用

较好的实践

  1. 非docker环境,可以使用命令行传参
  2. docker环境,可以使用System properties.

传参的两种方式

  1. -Dspring.profiles.active=dev -Dserver.port=8080,这是java的方式
  2. --spring.profiles.active=dev --server.port=8080这是springBoot特有的方式,这个是命令行参数,所以应该放到最后面

spring给的方式挺多的,但是感觉java的方式就够了,至于--这种命令行的方式,是springBoot自创的,只有springBoot封装了一下,你知道就行了,

jar的配置文件

自从springBoot方便的使用可执行jar以后,问题就来了,改jar里面的配置文件很麻烦怎么办,这是一个问题,不过spring早想到这了这点,所以,它又提供了优先级的方案,大概是这样

From the classpath

  1. The classpath root
  2. The classpath /config package

From the current directory

  1. The current directory
  2. The /config subdirectory in the current directory
  3. Immediate child directories of the /config subdirectory

没错,使用配置文件的时候,也有很多优先级,classpath的优先级低,当前文件夹的优先级高,而且当前文件夹的时候,还有优先级

较佳实践

  1. 直接当前文件夹配置文件
  2. config配置文件
  3. 使用spring.config.location显式指定,但是应该没太大必要,一般,前两种就够了,毕竟,约定大于配置,既然约定好了,就用

文档引用地址

其实spring文档真的很不错
spring2.7的文档额外配置特性

总结

了解一下springBoot配置的优先级,以及命令行传参的两种方式,还有使用文件配置的时候,如果jar外面配置,基本够用了