java - Spring:将属性文件注入(inject) map

标签 java spring

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

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

问题:如何将这些属性注入(inject) Map<String, String> ?你能举个例子吗?

最佳答案

如果是 XML 配置

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

由于属性实现了映射,您可以将其作为构造函数提供

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

请注意 Spring 将完成所有 the required generic type conversions

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 类中进行配置 - 参见 Converting java.util.Properties To HashMap<string,string> .

关于java - Spring:将属性文件注入(inject) map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21278951/

相关文章:

Java 节点交换

java - Java 导入如何工作?

java - Spring : Logging wont get disabled. 默认转为 Debug

spring - Spring 安全注销后,grails.app.context丢失

java - 应用程序/ war 部署失败时如何关闭tomcat服务?

java - 在行中找不到可执行代码

java - 继续向类(class)提供信息

java - 将 reSTLet 与 Eclipse Virgo 结合使用

java - 如何减少 Initializing Spring root WebApplicationContext 时间?

spring - 在 Spring Security OAuth2 中使用用户名密码授权中的刷新 token 请求新的访问 token