VB_
VB_

Reputation: 45732

Spring: inject properties file into map

I've got a property file below:

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

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

Upvotes: 6

Views: 10120

Answers (1)

Boris Treukhov
Boris Treukhov

Reputation: 17784

In case of XML configuration

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>

please note that Spring will do all 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.

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>.

Upvotes: 12

Related Questions