Spring Boot 应用程序中特定于环境的 application.properties 文件

在我的 SpringBoot 应用程序中,我想创建特定于环境的属性文件。我在 war 中的应用程序的打包类型,并且我正在嵌入的 tomcat 中执行它。我使用 st 并从 st 本身执行 main。

  1. 我是否可以使用特定于环境的属性文件,比如 application-${ env-value } . properties?

在上面的例子中,env-value 的值为 local/devl/test/prod

  1. 在哪里设置 env-value 文件? 对于 local,我可以通过 st 将其设置为 jvm 参数

  2. 在 Spring Boot 应用程序中读取 application.properties 的用户。

  3. 如何加载特定于环境的属性文件?对于 ex-if 我在特定于环境的属性文件中设置数据库 uid、 pwd、 schema 等,在这种情况下,数据源能够理解其中的属性吗?

  4. 我能同时使用 application.properties 和 application-local. properties 文件吗?

145206 次浏览

Spring Boot already has support for profile based properties.

Simply add an application-[profile].properties file and specify the profiles to use using the spring.profiles.active property.

-Dspring.profiles.active=local

This will load the application.properties and the application-local.properties with the latter overriding properties from the first.

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
@PropertySource("application-${spring.profiles.active}.properties"),
@PropertySource("my-special-${spring.profiles.active}.properties"),
@PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

we can do like this:

in application.yml:

spring:
profiles:
active: test //modify here to switch between environments
include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
port: 5000

and in application-local.yml:

server:
address: 0.0.0.0
port: 8080

then spring boot will start our app as we wish to.

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT