Здесь немного в убытке. У меня есть пример приложения/доказательство концепции, которое я пытаюсь заставить работать со следующей конфигурацией:
Уровень 1: библиотека, использующая компоненты Spring, которая должна быть скрыта от библиотек/приложений конечного пользователя.
Уровень 2: библиотека, которая использует вышеупомянутую библиотеку, но в остальном не реализована в Spring. Достаточно умен, чтобы автоматически установить контекст Spring, но скрыть детали этого от пользователей библиотеки.
Уровень 3: приложение, использующее библиотеку «промежуточного программного обеспечения» на уровне 2, также не поддерживающее Spring.
У меня все это работает так, как я ожидаю, даже имея возможность установить активный профиль (spring.profiles.active) и получить правильный файл свойств из пути к классам приложения уровня 3. Вот странность:
Если я запускаю приложение из своей IDE (IntelliJ) и передаю активный профиль в командной строке, все работает как положено. Значения, которые я загружаю из своего «производственного» файла свойств, переопределяют значения в файле свойств по умолчанию. То есть значение ключа X в application-production.properties
переопределяет значение X в application.properties
.
Все хорошо, верно? Хорошо, попробуйте запустить банку из командной строки, сделав то же самое (java -Dspring.profiles.active=production -jar my-app-1.0-SNAPSHOT-full.jar
). Я вижу в журнале отладки, что файл свойств «производства» выбран, но файл по умолчанию имеет приоритет. То есть значение в application.properties
используется, хотя в контексте Spring ясно указано, что «производство» активно, и он отлично находит и загружает application-production.properties
.
Э, ЧТО?!
Кто-нибудь еще сталкивался с этим, и если да, то какие обходные пути? Я использую Spring IO Platform Brussels-SR5, которая включает версию 4.3.11.RELEASE для spring-core, spring-context и др. 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/]]
Итак, вы можете видеть здесь, что для файла свойств, специфичного для профиля, устанавливается более низкий приоритет, чем для универсального файла свойств. Также,
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!
Там, где я фактически вызываю компонент, я добавил код, чтобы показать, какой профиль активен и что содержит значение свойства.
Как я уже говорил ранее, это работает корректно при запуске из моей IDE, но не из jar-файла.
РЕДАКТИРОВАНИЕ №2
Поэтому я попытался удалить файлы свойств из банки и запустить их в текущем каталоге. Тот же результат. Сбросил банку в папку, добавил файлы свойств в эту папку ... работает как положено. Так что это определенно как-то связано с банкой в миксе.