美文网首页Spring Boot
(三)如何修改Spring Boot应用程序的配置

(三)如何修改Spring Boot应用程序的配置

作者: 傅永德 | 来源:发表于2016-10-17 16:33 被阅读0次

Spring Boot的配置方式

Spring Boot中遵循了约定优于配置的原则,故我们在构建Spring Boot Application时非常轻松。在实际生产过程中,我们需要针对工程做额外的配置,那么我们该怎么使用额外的配置呢?

Spring Boot允许使用外部化配置,以便我们可以在不同的环境中使用相同的应用程序代码。 这些配置可以使用属性文件,YAML文件,环境变量和命令行参数等来外化配置。 属性值可以使用@Value注释直接注入到bean中,通过Spring的Environment抽象访问或通过@ConfigurationProperties绑定到结构化对象。

Spring Boot使用一个非常特殊的PropertySource顺序,该顺序被设计为允许对值进行明智的重写。 属性按以下顺序考虑:

  1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).

  2. @TestPropertySource annotations on your tests.

  3. @SpringBootTest#properties annotation attribute on your tests.

  4. Command line arguments.

  5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)

  6. ServletConfig init parameters.

  7. ServletContext init parameters.

  8. JNDI attributes from java:comp/env.

  9. Java System properties (System.getProperties()).

  10. OS environment variables.

  11. A RandomValuePropertySource that only has properties in random.*.

  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)

  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)

  14. Application properties outside of your packaged jar (application.properties and YAML variants).

  15. Application properties packaged inside your jar (application.properties and YAML variants).

  16. @PropertySource annotations on your @Configuration classes.

  17. Default properties (specified using SpringApplication.setDefaultProperties).

本文主要讨论在application.properties配置文件中来进行额外的配置,其他的使用配置的方法详情参考这里

application.properties文件的使用

SpringApplication将从以下位置的application.properties文件加载属性,并将它们添加到Spring环境:

  1. 当前路径下的/config子目录。
  2. 当前路径。
  3. classpath路径下的/config子路径。
  4. classpath路径

列表按优先级排序(在列表中较高的位置定义的属性覆盖在较低位置定义的属性)。

上文的程序中,在resources目录添加application.properties文件,添加如下配置

#tomcat端口号
server.port=8888

启动Spring Boot程序,此时我们访问程序的端口号就变为了8888。

更多application.properties的配置,请参考官方文档

本文示例程序请点此获取。
详细资料请参考Spring Boot官网

相关文章

网友评论

    本文标题:(三)如何修改Spring Boot应用程序的配置

    本文链接:https://www.haomeiwen.com/subject/xrqzyttx.html