目前,我的 src/main/resources
文件夹中有一些属性文件:
- application.properties
- application-dev.properties
- application-test.properties
现在,当我指定一个配置文件时,它会加载该配置文件的特定文件和通用 application.properties
,并用前者覆盖所有内容。
但是,当我的应用程序部署在生产中时,不会传递任何配置文件,因此 application.properties
必须 是我的生产文件。
这很好,因为我可以覆盖配置文件特定的所有内容。然而,有一个问题;在生产中,我现在需要设置:
spring.datasource.jndi-name=jdbc/appname
当我将其添加到 application.properties
时,每个配置文件也会继承它,然后,当我运行开发服务器或测试时,它会给出以下错误:
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
因为我确实不在我自己的环境中使用这个 JNDI 东西;我使用以下属性:
spring.datasource.url=jdbc:url
spring.datasource.username=user
spring.datasource.password=pass
我的问题是:我一生都无法覆盖这个属性。如果我在环境特定文件中添加任何这些内容,它将被忽略并且错误仍然存在:
spring.datasource.jndi-name= # empty string, does nothing
spring.datasource.jndi-name=<null> # read somewhere it meant null, doesn't work
spring.datasource.jndi-name=${inexistentProp} # I though it might return null, but gives an error
那么,我能做什么呢?我想到了几个解决方案:
- 一种在 Spring 属性文件中将属性值设置为正确的 null 或未定义的方法(因为空不起作用)
- 一种将通常继承的属性文件更改为其他内容的方法(我尝试过@PropertySource,但它只会添加更多选项,最终总是回退到 application.properties)
- 通过属性文件完全禁用 JNDI,尽管有前一个属性(我按照 here 尝试了
spring.jndi.ignore=true
,但无济于事)
但是要么我不知道怎么做,要么它们不起作用。
最佳答案
Spring Boot 文档,24.4 Profile-specific Properties :
In addition to
application.properties
files, profile-specific properties can also be defined by using the following naming convention:application-{profile}.properties
. TheEnvironment
has a set of default profiles (by default,[default]
) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties fromapplication-default.properties
are loaded.
The
spring.profiles.include
property can be used to unconditionally add active profiles.
因此,创建一个具有以下属性的 application-default.properties
文件:
spring.profiles.include=prod
现在将 spring.datasource.jndi-name=jdbc/appname
属性从 application.properties
文件移动到 application-prod.properties
文件。
当您使用特定配置文件运行代码时,将不会使用prod
配置文件,并且spring.datasource.jndi-name
将是未定义的。
当您在生产环境中运行代码时,如果未指定配置文件,则默认包含 prod
配置文件,并且将定义 spring.datasource.jndi-name
。
您当然可以将生产属性放在 application-default.properties
本身中,但上述方法可以让您更清楚地了解您在做什么。
如果您最终拥有多个配置文件,这也会让事情变得更容易。例如。你有prod
vs dev
vs test
。但是,如果您有一组独立的配置文件(例如 foo
与 bar
),并且默认生产环境应该是 prod,foo
,该怎么办?允许备用生产环境使用 prod,bar
,并且每个环境都可以单独测试(test,foo
和 test,bar
)。
通过使用默认
配置文件仅包含其他配置文件,而不定义任何属性,您现在可以根据需要手动混合和匹配配置文件。
关于java - Spring 属性文件将属性设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458359/