2011-01-12 2 views
0

У меня есть Spring Java config object, который загружает мои свойства, но не переопределяет токены MessageSource.Ошибка получения Spring PropertyPlaceholderConfigurer для переопределения значений MessageSource

@Configuration 
@SuppressWarnings("unused") 
public class PropertyConfiguration { 

public static final String PROPERTY_OVERRIDE_URL = "d2.config.location"; 

@Bean 
public UrlResource propertyOverrideUrl() { 
    String propertyOverrideUrl = System.getProperty(PROPERTY_OVERRIDE_URL); 

    UrlResource overrideUrl = null; 
    // just add a bogus url as to not get a malformed URL 
    try{ 
     overrideUrl = new UrlResource(
       (propertyOverrideUrl == null || "".equals(propertyOverrideUrl)? "file:///FILENOTFOUND" : propertyOverrideUrl) 
     ); 
    } catch (MalformedURLException e){ 
     // Set the URL to a dummy value so it will not break. 
     try{ 
      overrideUrl = new UrlResource("file:///FILENOTFOUND"); 
     } catch (MalformedURLException me){ 
      // this is a valid URL, but will not be found at runtime. 
     } 
    } 
    return overrideUrl; 
} 

@Bean 
@DependsOn("propertyOverrideUrl") 
@Lazy(false) 
public ContextAwarePropertyPlaceholderConfigurer propertyPlaceholderConfigurer() 
throws IOException{ 
    return new ContextAwarePropertyPlaceholderConfigurer(){{ 
     setLocations(new Resource[]{ 
      new ClassPathResource("application_prompts.properties"), 
      new ClassPathResource("application_webservice.properties"), 
      new ClassPathResource("application_externalApps.properties"), 
      new ClassPathResource("application_log4j.properties"), 
      new ClassPathResource("application_fileupload.properties"), 
      //Must be last to override all other resources 
      propertyOverrideUrl() 
     }); 
     setIgnoreResourceNotFound(true); 
    }}; 
} 

Когда я запускаю тест единицы на свойстве javaconfig это прекрасно:

@Test 
public void testOverrides__Found() throws Exception { 
    setOverrideUrlSystemProperty("/target/test/resources/override-test.properties"); 
    context = SpringContextConfigurationTestHelper.createContext(); 
    context.refresh(); 

    String recordedPaymentConfirmationPath = 
      (String)context.getBean("recordedPaymentConfirmationPath"); 
    assertThat(recordedPaymentConfirmationPath, is("test/dir/recordings/")); 

    String promptServerUrl = 
      (String)context.getBean("promptServerUrl"); 
    assertThat(promptServerUrl, is("http://test.url.com")); 
} 

Но когда я пытаюсь значение MessageSource, она все еще имеет старое значение:

@Test 
public void testOverrides__XYZ() throws Exception { 
    setOverrideUrlSystemProperty("/target/test/resources/override-test.properties"); 
    context = SpringContextConfigurationTestHelper.createContext(); 
    context.refresh(); 

    String promptServerUrl = (String)context.getMessage("uivr.prompt.server.url", 
        new Object[] {}, Locale.US); 

    assertThat(promptServerUrl, is("http://test.url.com")); 
} 

выход:

[junit] Testcase: testOverrides__XYZ took 0.984 sec 
[junit]  FAILED 
[junit] 
[junit] Expected: is "http://test.url.com" 
[junit]  got: "http://24.40.46.66:9010/agent-ivr-prompts/" 
[junit] 
[junit] junit.framework.AssertionFailedError: 
[junit] Expected: is "http://test.url.com" 
[junit]  got: "http://24.40.46.66:9010/agent-ivr-prompts/" 
[junit] 
[junit]  at  com.comcast.ivr.agent.configuration.PropertyOverrideConfigurationTest.testOverrides__XYZ(PropertyOverrideConfigurationTest.java:114) 

Может кто-то пожалуйста, помогите мне найти способ, чтобы переопределить MessageSource, потому что это то, что используется в наших шаблонах скоростей:

#set($baseUrl = "#springMessage('uivr.prompt.server.url')") 

Я добавил некоторые протоколирования:

@Override 
    protected void loadProperties(Properties props) throws IOException { 
    super.loadProperties(props); 
    super.mergeProperties(); 
    if(logger.isDebugEnabled()){ 
     System.out.println("--------------------"); 
     for (Map.Entry entry : props.entrySet()) { 
      System.out.println(entry.getKey() + ":" + entry.getValue()); 
      logger.info(entry.getKey() + ":" + entry.getValue()); 
     } 
     System.out.println("--------------------"); 
    } 
} 

И значения печатаются, как и ожидалось ,

... 
[junit] uivr.prompt.server.url:http://test.url.com 
... 

ответ

0

Пара боковых заметки о аннотаций, используемых на вашем propertyPlaceholderConfigurer()@Bean метода:

  • @Lazy(false) не является необходимым, так как это уже по умолчанию. Вы можете пропустить это.
  • @DependsOn("propertyOverrideUrl") не является необходимым, так как зависимость уже установлена ​​путем вызова propertyOverrideUrl() внутри propertyPlaceholderConfigurer()

на ваш фактический вопрос, это немного трудно ответить, потому что я не уверен, что ContextAwareProperyPlaceholderConfigurer делает (я m, предполагая, что это настраиваемый компонент, поскольку он не является частью основной Spring Framework).

В этом случае может возникнуть недоразумение. Spring PropertyPlaceholderConfigurer (PPC) и друзья работают с определениями обработки после обработки, чтобы заменить ${...} заполнителями, но не взаимодействовать с объектами MessageSource. Таким образом, поведение, которое вы описываете, я полагаю, как и ожидалось: вы увидите «правильный» URL-адрес при опросе компонента (потому что он был обработан после вашего PPC), однако вы видите «неправильный» URL-адрес при опросе сообщения источника (поскольку он полностью не связан с пост-обработкой PPC).

Надеюсь, это поможет.