【问题标题】:spring.profiles.active not being honored from command line, but works in IDEspring.profiles.active 不被命令行尊重,但在 IDE 中工作
【发布时间】:2017-10-06 00:41:31
【问题描述】:

这里有点失落。我有一个示例应用程序/概念验证,我正在尝试使用以下配置:

第 1 层:利用 Spring 组件的库,隐藏在最终用户库/应用程序之外。

第 2 层:引入上述库的库,但在其他方面未实现 Spring。足够聪明地自动建立 Spring 上下文,但对库的用户隐藏它的细节。

第 3 层:在第 2 层中使用“中间件”库的应用程序,同样不支持 Spring。

我已经按照我的预期完成了所有这些工作,甚至能够设置活动配置文件 (spring.profiles.active) 并从第 3 层应用程序的类路径中获取正确的属性文件。奇怪的是:

如果我从我的 IDE (IntelliJ) 运行应用程序并让它通过命令行上的活动配置文件,一切都会按预期工作。我从“生产”属性文件加载的值会覆盖默认属性文件中的值。也就是说,application-production.properties 中键 X 的值会覆盖 application.properties 中 X 的值。

一切都好,对吧?好的,尝试从命令行运行 jar 做同样的事情 (java -Dspring.profiles.active=production -jar my-app-1.0-SNAPSHOT-full.jar)。我在调试日志中看到“生产”属性文件被拾取,但默认文件优先。也就是说,application.properties 中的值正在被使用,即使 Spring 上下文明确指出“生产”处于活动状态,并且它找到并加载 application-production.properties 就好了。

诶,哇?!

有没有其他人经历过这种情况,如果有,有什么解决方法吗?我正在引入 Spring IO Platform Brussels-SR5,其中包括 spring-core、spring-context 等的 4.3.11.RELEASE 版本。应用程序的 jar 是一个包含所有依赖项的带阴影的 jar。这两个库 jar 没有阴影。

编辑

日志比较长...打算剪到相关部分...

william@jessie:/mnt/builds/william/src/mixed-spring-legacy-app$ java -Dspring.profiles.active=production -jar example-app/target/example-app-1.0-SNAPSHOT-full.jar 
20:20:18.726 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding PropertySource 'systemProperties' with lowest search precedence
20:20:18.732 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding PropertySource 'systemEnvironment' with lowest search precedence
20:20:18.733 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [MapPropertySource@20557198 {name='systemProperties', properties={java.runtime.name=OpenJDK Runtime Environment, sun.boot.library.path=/usr/lib/jvm/java-8-openjdk-i386/jre/lib/i386, java.vm.version=25.141-b15, java.vm.vendor=Oracle Corporation, java.vendor.url=http://java.oracle.com/, path.separator=:, java.vm.name=OpenJDK Server VM, file.encoding.pkg=sun.io, user.country=US, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=unknown, java.vm.specification.name=Java Virtual Machine Specification, user.dir=/mnt/builds/william/src/mixed-spring-legacy-app, java.runtime.version=1.8.0_141-8u141-b15-1~deb9u1-b15, java.awt.graphicsenv=sun.awt.X11GraphicsEnvironment, java.endorsed.dirs=/usr/lib/jvm/java-8-openjdk-i386/jre/lib/endorsed, os.arch=i386, spring.profiles.active=production, java.io.tmpdir=/tmp, line.separator=
, java.vm.specification.vendor=Oracle Corporation, os.name=Linux, sun.jnu.encoding=UTF-8, java.library.path=/usr/java/packages/lib/i386:/usr/lib/i386-linux-gnu/jni:/lib/i386-linux-gnu:/usr/lib/i386-linux-gnu:/usr/lib/jni:/lib:/usr/lib, java.specification.name=Java Platform API Specification, java.class.version=52.0, sun.management.compiler=HotSpot Tiered Compilers, os.version=4.9.0-3-686-pae, user.home=/home/william, user.timezone=America/New_York, java.awt.printerjob=sun.print.PSPrinterJob, file.encoding=UTF-8, java.specification.version=1.8, java.class.path=example-app/target/example-app-1.0-SNAPSHOT-full.jar, user.name=william, java.vm.specification.version=1.8, sun.java.command=example-app/target/example-app-1.0-SNAPSHOT-full.jar, java.home=/usr/lib/jvm/java-8-openjdk-i386/jre, sun.arch.data.model=32, user.language=en, java.specification.vendor=Oracle Corporation, awt.toolkit=sun.awt.X11.XToolkit, java.vm.info=mixed mode, java.version=1.8.0_141, java.ext.dirs=/usr/lib/jvm/java-8-openjdk-i386/jre/lib/ext:/usr/java/packages/lib/ext, sun.boot.class.path=/usr/lib/jvm/java-8-openjdk-i386/jre/lib/resources.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/lib/rt.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/lib/jsse.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/lib/jce.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/lib/charsets.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/lib/jfr.jar:/usr/lib/jvm/java-8-openjdk-i386/jre/classes, java.vendor=Oracle Corporation, file.separator=/, java.vendor.url.bug=http://bugreport.sun.com/bugreport/, sun.io.unicode.encoding=UnicodeLittle, sun.cpu.endian=little, sun.cpu.isalist=}}, SystemEnvironmentPropertySource@5592464 {name='systemEnvironment', properties={ .. truncated ..}}]
20:20:18.765 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [tech/chihuahua/examples/] to resources [URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/]]
20:20:18.767 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in jar file [file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar]
20:20:18.786 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:tech/chihuahua/examples/**/*.class] to resources [URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/client/GreetingClient.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/client/GreetingClientImpl.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/client/GreetingClientFactory.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryProductionContext.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryStagingContext.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryDefaultContext.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryIntegrationTestContext.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryProductionContext$ProductionProperties.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryIntegrationTestContext$IntegrationTestProperties.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryStagingContext$StagingProperties.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryDefaultContext$DefaultProperties.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/Profiles.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/LibraryContextProvider.class], URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/service/GreetingService.class]]
20:20:18.825 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryProductionContext.class]
20:20:18.825 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryStagingContext.class]
20:20:18.831 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryDefaultContext.class]
20:20:18.832 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryIntegrationTestContext.class]
20:20:18.840 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'spring.profiles.active' in PropertySource 'systemProperties' with value of type String
20:20:18.840 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryProductionContext$ProductionProperties.class]
20:20:18.842 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/config/LibraryDefaultContext$DefaultProperties.class]
20:20:18.845 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/service/GreetingService.class]
20:20:18.858 [main] INFO org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@16f64b1: startup date [Thu Oct 05 20:20:18 EDT 2017]; root of context hierarchy
20:20:18.858 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext@16f64b1: org.springframework.beans.factory.support.DefaultListableBeanFactory@1629756: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,libraryProductionContext,libraryStagingContext,libraryDefaultContext,libraryIntegrationTestContext,libraryProductionContext.ProductionProperties,libraryDefaultContext.DefaultProperties,greetingService]; root of factory hierarchy
20:20:18.883 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
20:20:18.883 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
20:20:18.902 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
20:20:18.904 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
20:20:18.930 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding PropertySource 'class path resource [application-production.properties]' with lowest search precedence
20:20:18.936 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding PropertySource 'class path resource [application.properties]' with search precedence immediately higher than 'class path resource [application-production.properties]'
20:20:18.938 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [tech/chihuahua/examples/] to resources [URL [jar:file:/mnt/builds/william/src/mixed-spring-legacy-app/example-app/target/example-app-1.0-SNAPSHOT-full.jar!/tech/chihuahua/examples/]]

因此,您可以在此处看到特定配置文件的属性文件被设置为低于 catch-all 属性文件的优先级。还有,

20:20:19.128 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'greetingService' to allow for resolving potential circular references
20:20:19.128 [main] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected element of bean 'greetingService': AutowiredMethodElement for public void tech.chihuahua.examples.service.GreetingService.setEnvironment(org.springframework.core.env.Environment)
20:20:19.130 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'environment'
20:20:19.130 [main] DEBUG org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'greetingService' to bean named 'environment'
    Active profile: production
20:20:19.179 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'tech.chihuahua.examples.greeting.format' in PropertySource 'class path resource [application.properties]' with value of type String
    tech.chihuahua.examples.greeting.format set to 'Hi, %s!'
20:20:19.179 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'greetingService'
20:20:19.179 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'propertySourcesPlaceholderConfigurer'
20:20:19.180 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
20:20:19.210 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@1afa13b]
20:20:19.210 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
20:20:19.212 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
20:20:19.214 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'greetingService'
20:20:19.214 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'tech.chihuahua.examples.greeting.format' in PropertySource 'class path resource [application.properties]' with value of type String
Hi, Jack!

在我实际调用 bean 的地方,我添加了代码来显示哪些配置文件处于活动状态,以及属性值包含什么。

正如我之前所说,这在从我的 IDE 运行时可以正常工作,但不能从 jar 文件运行。

编辑#2

所以我尝试从 jar 中删除属性文件并在当前目录中运行它们。结果相同。将罐子转储到一个文件夹中,将属性文件添加到该文件夹​​中......就像它应该的那样工作。所以这绝对是和罐子有关。

【问题讨论】:

  • 顺便说一句,我试过重启我的IDE,重启我的机器等,以防万一它有某种脑抽筋,但无济于事。另外,我没有在第 1 层库中使用 Spring Boot,因为它在使用 Spring 的同时,需要尽可能地小,而且 Boot 往往会引入许多无用的额外依赖项我。
  • 你能贴出实际的日志吗?

标签: java spring maven intellij-idea spring-profiles


【解决方案1】:

所以我终于想出了一个解决方法。至于为什么它使用文件夹中的所有类/属性文件而不是在 jar 中时,我能给出的最佳答案是“紫色,因为外星人不戴帽子。”

无论如何,我必须做的是添加另一个特定于“默认”配置文件的“配置文件”属性类。这将接收“application-default.properties”文件中的任何内容,并且只有在没有激活其他配置文件时才会被激活。 “application.properties”文件不应包含将根据活动配置文件覆盖的数据。

如何工作的代码示例...

Catch-all/root 配置

package tech.chihuahua.examples.config;

import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import tech.chihuahua.examples.service.GreetingService;

@Configuration
@ComponentScan("tech.chihuahua.examples")
public class LibraryContext {

    @Configuration
    @PropertySources({
            @PropertySource(
                    value = "${spring.config.location}/application.properties",
                    ignoreResourceNotFound = true),
            @PropertySource(
                    value = "classpath:application.properties",
                    ignoreResourceNotFound = true)
    })
    static class ApplicationProperties {}

    @Bean
    GreetingService greetingService() {
        return new GreetingService();
    }

    @Bean
    static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

默认值,当没有配置文件处于活动状态时

package tech.chihuahua.examples.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;

@Configuration
public class LibraryDefaultContext {

    @Profile("default")
    @Configuration
    @PropertySources({
            @PropertySource(
                    value = "${spring.config.location}/application-default.properties",
                    ignoreResourceNotFound = true),
            @PropertySource(
                    value = "classpath:application-default.properties",
                    ignoreResourceNotFound = true)
    })
    static class DefaultProperties {}

}

生产资料有效

package tech.chihuahua.examples.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import tech.chihuahua.examples.Profiles;

@Configuration
public class LibraryProductionContext {

    @Profile(Profiles.PRODUCTION)
    @Configuration
    @PropertySources({
            @PropertySource(
                    value = "${spring.config.location}/application-production.properties",
                    ignoreResourceNotFound = true),
            @PropertySource(
                    value = "classpath:application-production.properties",
                    ignoreResourceNotFound = true)
    })
    static class ProductionProperties {}

}

暂存配置文件有效

package tech.chihuahua.examples.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import tech.chihuahua.examples.Profiles;

@Configuration
public class LibraryStagingContext {

    @Profile(Profiles.STAGING)
    @Configuration
    @PropertySources({
            @PropertySource(
                    value = "${spring.config.location}/application-staging.properties",
                    ignoreResourceNotFound = true),
            @PropertySource(
                    value = "classpath:application-staging.properties",
                    ignoreResourceNotFound = true)
    })
    static class StagingProperties {}

}

一切就绪后,构建 uber-jar。如果需要,将属性文件包含在 jar 中,或者确保它们在您机器上的文件夹中可用(例如 /etc/my-app)。

# The general application configuration settings go here.
/etc/my-app/application.properties

# The default configuration settings go here
# (e.g. configure the application to use an in-memory database)
/etc/my-app/application-default.properties

# The production configuration settings go here
# (e.g. configure the application to use your production database)
/etc/my-app/application-production.properties

# The staging configuration settings go here
# (e.g. configure the application to use a staging/test database)
/etc/my-app/application-staging.properties

使用默认设置执行应用

如果没有指定其他配置文件,Spring 会自动将“默认”配置文件设置为活动状态。所以这里会选择“application-default.properties”文件,并使用它的配置。

# Using the properties files in the classpath in the jar
java -jar my-app-1.0-SNAPSHOT-full.jar

# Using the properties files on the file system
java -Dspring.config.location=file:///etc/my-app \
     -jar my-app-1.0-SNAPSHOT-full.jar

在生产配置文件处于活动状态的情况下执行应用

通过启用“生产”配置文件,将不会激活“默认”配置文件。因此,“application-default.properties”被忽略,“application-production.properties”被加载。

# Using the properties files in the classpath in the jar
java -Dspring.profiles.active=production \
     -jar my-app-1.0-SNAPSHOT-full.jar

# Using the properties files on the file system
java -Dspring.profiles.active=production \
     -Dspring.config.location=file:///etc/my-app \
     -jar my-app-1.0-SNAPSHOT-full.jar

在暂存配置文件处于活动状态的情况下执行应用

与之前相同,只是使用“staging”配置文件而不是“production”。

# Using the properties files in the classpath in the jar
java -Dspring.profiles.active=staging \
     -jar my-app-1.0-SNAPSHOT-full.jar

# Using the properties files on the file system
java -Dspring.profiles.active=staging \
     -Dspring.config.location=file:///etc/my-app \
     -jar my-app-1.0-SNAPSHOT-full.jar

希望这有助于节省时间和烦恼。

【讨论】:

    【解决方案2】:

    将属性名称用引号括起来,如下所示并尝试。这应该有效:

    java -D"spring.profiles.active"=production -jar example-app/target/example-app-1.0-SNAPSHOT-full.jar 
    

    请确认建议的更改是否能解决问题。

    【讨论】:

      猜你喜欢
      • 2015-05-20
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2017-09-24
      • 1970-01-01
      相关资源
      最近更新 更多