2013-12-03 3 views
1

Я хотел обрабатывать несколько сред, используя свойство-placeholder + spring.profiles.active. Я устанавливаю мою установку spring.profiles.active в качестве параметра VM и моя весна XML выглядит, как показано ниже:Свойство не оценивалось весной xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:util="http://www.springframework.org/schema/util" 

xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> 


<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
     <list> 
      <value>classpath:rcwkstn-automation-framework${spring.profiles.active}.properties</value> 
     </list> 
    </property> 
</bean> 

я загружаю контекст пружины с помощью SpringJUnit4ClassRunner, как показано ниже:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"classpath:rcwkstn-automation-framework.xml"}) 

проблема заключается в том, что когда я запускаю мой код я получаю:

java.lang.IllegalStateException: Failed to load ApplicationContext 
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) 
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122) 
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109) 
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) 
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [rcwkstn-automation-framework${spring.profiles.active}.properties] cannot be opened because it does not exist 
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:87) 
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694) 
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:669) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) 
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120) 
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) 
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) 
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) 
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) 
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) 
    ... 25 more 
Caused by: java.io.FileNotFoundException: class path resource [rcwkstn-automation-framework${spring.profiles.active}.properties] cannot be opened because it does not exist 
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) 
    at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:143) 
    at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:98) 
    at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:175) 
    at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:156) 
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:78) 
    ... 34 more 

это Лоо ks, как $ {spring.profiles.active}, не оценивается и не рассматривается как литерал. Кто-нибудь знает, что здесь может быть неправильно?

+0

Как загружается этот файл конфигурации? Можете ли вы опубликовать полный стек? Кроме того, вместо прямого указания компонента bean рекомендуется использовать пространство имен '' –

+0

Я также пробовал как вы упомянули с тем же результатом – czajek

+0

И как вы передаете недвижимость? Убедитесь, что свойство передано как свойство -D. Замена будет работать только для системных свойств или переменных среды. –

ответ

1

Сам фасоль PropertyPlaceholderConfigurer используется для указания файлов свойств, которые необходимо загрузить, чтобы можно было разрешить владельцам мест. Таким образом, очевидно, что если вы дадите владельцу места собственности в нем, он не будет загружен, так как компонент еще не создан и свойства еще не загружены.

Вам либо нужно указать полное имя файлов свойств как таковых, либо перенести все файлы свойств в папку и загрузить все из этой папки, указав *.properties (загрузите все файлы свойств).

Пример:

<value>classpath:config.properties</value> // full file name 
<value>file:///${CATALINA_HOME}/prop-folder/*.properties</value> // load all props 
+0

Он должен работать, мы также делаем что-то similair (со свойством среды для загрузки среды укажите файлы свойств). Работает как шарм, но он будет работать только для свойств системы (-D) или свойств среды. –

+0

'config.properties', который я задал, является определяемым пользователем файлом свойств, и даже второй пример загрузит все пользовательские файлы свойств, присутствующие в этой папке. – SudoRahul

+0

Правильно (поверьте мне, я знаю, как работает весенняя загрузка ресурсов). Но, как упоминалось, он отлично работает с заполнителями. Мы передаем что-то вроде этого 'file: $ {CONFIG_HOME}/$ {APP_CODE}/$ {ENV_CODE} /' на Placeholder без каких-либо проблем. Где «CONFIG_HOME» - это переменная среды, а все остальные определяются во время выполнения. –

Смежные вопросы