Spring Boot的配置方式
Spring Boot中遵循了约定优于配置的原则,故我们在构建Spring Boot Application时非常轻松。在实际生产过程中,我们需要针对工程做额外的配置,那么我们该怎么使用额外的配置呢?
Spring Boot允许使用外部化配置,以便我们可以在不同的环境中使用相同的应用程序代码。 这些配置可以使用属性文件,YAML文件,环境变量和命令行参数等来外化配置。 属性值可以使用@Value注释直接注入到bean中,通过Spring的Environment抽象访问或通过@ConfigurationProperties绑定到结构化对象。
Spring Boot使用一个非常特殊的PropertySource顺序,该顺序被设计为允许对值进行明智的重写。 属性按以下顺序考虑:
Devtools global settings properties on your home directory (
~/.spring-boot-devtools.propertieswhen devtools is active).@TestPropertySourceannotations on your tests.@SpringBootTest#propertiesannotation attribute on your tests.Command line arguments.
Properties from
SPRING_APPLICATION_JSON(inline JSON embedded in an environment variable or system property)ServletConfiginit parameters.ServletContextinit parameters.JNDI attributes from
java:comp/env.Java System properties (
System.getProperties()).OS environment variables.
A
RandomValuePropertySourcethat only has properties inrandom.*.Profile-specific application properties outside of your packaged jar (
application-{profile}.propertiesand YAML variants)Profile-specific application properties packaged inside your jar (
application-{profile}.propertiesand YAML variants)Application properties outside of your packaged jar (
application.propertiesand YAML variants).Application properties packaged inside your jar (
application.propertiesand YAML variants).@PropertySourceannotations on your@Configurationclasses.Default properties (specified using
SpringApplication.setDefaultProperties).
本文主要讨论在application.properties配置文件中来进行额外的配置,其他的使用配置的方法详情参考这里。
application.properties文件的使用
SpringApplication将从以下位置的application.properties文件加载属性,并将它们添加到Spring环境:
- 当前路径下的/config子目录。
- 当前路径。
- classpath路径下的/config子路径。
- classpath路径
列表按优先级排序(在列表中较高的位置定义的属性覆盖在较低位置定义的属性)。
在上文的程序中,在resources目录添加application.properties文件,添加如下配置
#tomcat端口号
server.port=8888
启动Spring Boot程序,此时我们访问程序的端口号就变为了8888。
更多application.properties的配置,请参考官方文档。
本文示例程序请点此获取。
详细资料请参考Spring Boot官网。