2014-10-06 75 views
1

我正在使用Spring 3.2並添加了一個屬性文件,我已經可以使用它將值注入到java類變量中。Spring 3.2屬性文件讀取動態屬性名稱(不是自動注入)

*<bean id="serverProperties" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
     <list> 
      <value>classpath:mysetof.properties</value> 
     </list> 
    </property> 
    <property name="placeholderPrefix" value="$server{" /> 
    <property name="ignoreResourceNotFound" value="false" /> 
    <property name="ignoreUnresolvablePlaceholders" value="false" /> 
</bean>* 

*@Value("#{$server{default.myproperty}}") 
private double defaultMyProperty* 

但是我有一些屬性,我需要動態地訪問。

如何訪問這些屬性?我已經使用了環境變量

*/** Spring var - used for accessing properties. */ 
@Autowired 
private Environment env;* 

,但我得到空值返回,當我試圖做到以下幾點:

propertyValue = env.getProperty("default.myproperty"); 

什麼是用於訪問屬性值而不是直接自動注入他們的最好的辦法。

這些屬性可能存在也可能不存在,並且可能存在大量的屬性,因此我不希望使用自動注射,因爲這將涉及設置大量變量。

在此先感謝。

+0

如果您希望環境中可用的屬性使用'@ PropertySource'來加載它們。 'PropertyPlaceholderConfigurer'不會將加載的屬性添加到'Environment'中,只會將它們添加到內部的'Properties'對象中。 – 2014-10-06 17:45:47

+0

我確實有這個 - 但我也必須添加@Configuration標記才能工作 - 然後它實例化了這個bean兩次(因爲我已經在一個上下文文件中)。理想情況下尋找方式在上下文文件中創建一個bean ...? – NottmTony 2014-10-07 10:16:53

+0

從'component-scan'中排除'@ Configuration'類,或者刪除所有xml並使用Java Config。 – 2014-10-07 10:18:47

回答

1

您可以嘗試在applicationContext.xml 如下使用CustomResourceBundleMessageSource我在core-messageSource豆配置messages.properties文件,並在您豆你可以做的messageSource豆application-messages.properties文件

<bean id="core-messageSource" 
     class="com.datacert.core.spring.CustomResourceBundleMessageSource"> 
     <property name="basenames"> 
      <list> 
       <value>messages</value> 
      </list> 
     </property> 
</bean> 

<bean id="messageSource" 
     class="com.datacert.core.spring.CustomResourceBundleMessageSource"> 
     <property name="parentMessageSource"> 
      <ref bean="core-messageSource"/> 
     </property> 
     <property name="basenames"> 
      <list> 
       <value>application-messages</value> 
      </list> 
     </property> 
</bean> 

然後低於

//I have security.cookie.timeout = 10 in my properties file 
ResourceBundleMessageSource bean = new ResourceBundleMessageSource(); 
bean.setBasename("application-messages"); 
String message = bean.getMessage("security.cookie.timeout", null, Locale.getDefault()); 
System.out.println("message = "+message)//will print message = 10 
+0

這是否意味着僅用於消息字符串?我有屬性是數字...? – NottmTony 2014-10-07 10:12:27

+0

@NottmTony您可以使用任何類型的資源包。你可以在我的案例中看到我正在讀取其值爲10的security.cookie.timeout屬性。我從文件讀取後解析字符串爲Integer.parseInt(message); – RanPaul 2014-10-07 14:33:32