【问题标题】:accessing map property from .properties file in application context (Spring)在应用程序上下文(Spring)中从 .properties 文件访问地图属性
【发布时间】:2015-07-06 15:13:10
【问题描述】:

在我的 .properties 文件中,我有这样的内容:

map = key1=value1, key2=value2

如何使用占位符访问 applicationContext.xml 中的键值对?我知道如果该属性只是一个字符串,那它就是:

<bean id="string_prop" class="java.lang.String">
    <constructor-arg value="${string.prop}"/>
</bean>

我也看过这个:

<util:map id="map_prop" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="key" value="value"></entry>
</util:map>

但我不确定如何从 .properties 文件中访问键值对。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    如果您想在 java 代码中访问地图,请使用如下方式,

    在 applicationContext.xml 中

    <bean id="mapName" class="java.util.HashMap">
            <constructor-arg ref="property" /> 
    </bean>
    
    <util:properties id="property" location="properName.properties"/>
    

    在java中:

     @Autowired
        protected HashMap<String, String> mapName;
    

    【讨论】:

    • 嗨。我这样做了,但随后 mapName hashmap 填充了属性文件中的所有内容,而不仅仅是 mapName 属性。
    • 获取值,用作 mapName.get("key");关键是你的“string.prop”。
    【解决方案2】:

    如果你想从 applicationContext 本身意味着使用如下,

    在 applicationContext.xml 中

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="propertyName.properties"/>
            <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>
    
    <bean id="string_prop" class="java.lang.String">
        <constructor-arg value="${string.prop}"/>
    </bean>
    

    在属性文件中:

    string.prop=some name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 2020-09-25
      相关资源
      最近更新 更多