Spring - properties filte to Map<String, Class<Object>>

404 Views Asked by At

I'm trying to load a class passing a properties file as parameter on the constructor but I'm getting a cast exception: java.lang.String cannot be cast to java.lang.Class. Can anyone help?

Here is my code:

myMap.properties

BAR=com.mycomp.myapp.Bar

application-context.xml looks like this:

<util:properties id="myMap" 
    location="classpath:myMap.properties" 
    local-override="false" 
    value-type="java.lang.Class" />   


<bean id="foo" class="com.mycomp.myapp.Foo">
    <constructor-arg name="myMap" ref="myMap"/>
</bean>

Foo.java

public class Foo {
    private Map<String, Class<Object>> myMap;

    public Foo(Map<String, Class<Object>> myMap){
        this.myMap = myMap;
        Class<Object> barClass = myMap.get("BAR"); //failure point
    }
}
1

There are 1 best solutions below

2
On

You can just do it like :

Context:

<context:property-placeholder location="classpath:myMap.properties"/>
<bean id="foo" class="com.mycomp.myapp.Foo">
  <constructor-arg value="${BAR}" />
</bean>

Foo:

public class Foo {
private String bar;

  public Foo(String bar){
      this.bar = bar;
  }
}

Or if you really need whole file you can just pass path to your property file and load it in constructor.