Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: inject properties file into map

Tags:

java

spring

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?

like image 721
VB_ Avatar asked Jan 22 '14 09:01

VB_


1 Answers

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

like image 54
Boris Treukhov Avatar answered Sep 17 '22 22:09

Boris Treukhov