Spring:将属性文件注入map [英] Spring: inject properties file into map

查看:967
本文介绍了Spring:将属性文件注入map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个属性文件:

I've got a property file below:

transition.s1=s2,s5
transition.s2=s4,s1
...................

问题:如何将这些属性注入 Map< String,String> ?你能提供一个例子吗?

Question: How to inject those properties into Map<String, String>? Can you provide an example?

推荐答案

如果是XML配置

public class StateGraph {
    public StateGraph(Map<String, String> a){ 
    ...
    }
    boolean getStateTransition(){
    ...
    }
}

属性实现你可以提供它作为构造函数的地图

as properties implements map you can supply it as constructor

<bean class="com.xxx.xxx.StateGraph">
    <constructor-arg>
        <util:properties location="classpath:props.properties"/> 
    </constructor-arg>
</bean>

请注意Spring会做所有所需的泛型类型转换

please note that Spring will do all the required generic type conversions


如果您使用的是Java 5或Java 6,您将意识到可以使用强类型集合
(使用通用类型)。
也就是说,可以声明一个Collection类型,使得
只能包含String元素(例如)。如果你使用Spring来
依赖注入一个强类型的集合到bean中,你可以使用
利用Spring的类型转换支持,这样你的强类型Collection实例的
元素在被添加到集合之前,将
转换为适当的类型。

If you are using Java 5 or Java 6, you will be aware that it is possible to have strongly typed collections (using generic types). That is, it is possible to declare a Collection type such that it can only contain String elements (for example). If you are using Spring to dependency inject a strongly-typed Collection into a bean, you can take advantage of Spring's type-conversion support such that the elements of your strongly-typed Collection instances will be converted to the appropriate type prior to being added to the Collection.

如果您使用的是程序化配置那么你必须自己在 @Configuration 类中进行 - 参见将java.util.Properties转换为HashMap< string,string>

If you are using the programmatic configuration instead then you will have to do it in the @Configuration class yourself - see Converting java.util.Properties To HashMap<string,string>.

这篇关于Spring:将属性文件注入map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆