0

I'm using spring 3.2.2 and what to inject some string in my .properties file into a class. But always get null.

In my applicationContext.xml:

....
<context:component-scan base-package="com.mypackage">
     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/
</context:component-scan>
<context:property-placeholder location="classpath:/config/core/abc.properties"/>
....

in abc.properties:

path=testpath

in java code:

package com.mypackage
@Component
public class myclass implements Imyclass {
    @Value("${path}")
    private String path; //this always is null
    ...
    public String getMyPath() {
        return path+"myclass";
    }
}

what I'm missing here?


[Edit]

the reason is in my code someone is calling new Imyclass(). Now there is another class impelement Imyclass:

package com.mypackage
@Component
public class myclass2 implements Imyclass {
    @Value("${path}")
    private String path; //this always is null
    ...
    public String getMyPath() {
        return path+"myclass2";
    }
}

The function calling the Imyclass:

public class myClassContext {
    public static String getPath(...){
        return getImyclass(...).getMyPath();
    }
    private static Imyclass getImyclass(....){
        Imyclass mc=null;
        if (.....) {
            mc=new myclass();
        }
        else{
            mc=new myclass2();
        }
        return state;
    }
}

What's the better way to manage the instance by Spring so the @value will inject correctly?

Do I have to inject both class into myClassContext as a property or use the @Configurable for both myclass and myclass2?

Linkivan
  • 39
  • 3
  • How do you use `Imyclass`? Often people do `new Imyclass()` and expect to have injected values in instances they create instead of using managed instances. – zapl May 27 '16 at 23:04
  • @zapl you are right! It's using the new Imyclass in code. But can you give me some more details on "using managed instances"? – Linkivan May 27 '16 at 23:41
  • Chances are it's not finding your properties file. Is this a war? Where in the path is the abc.properties located relative to the application root? Also, you may try removing the leading '/' – pczeus May 27 '16 at 23:43
  • spring can give you instances of every type as long as you autowire them into instances that are also managed by spring. Your code shouldn't have static methods like `getImyclass` because that doesn't work nicely with dependency injection. You should autowire an instance of myClassContext into the place that needs it and that instance with a non-static method can then give access to instances of other types, which itself got through spring. No `new` anywhere. – zapl May 29 '16 at 17:45

0 Answers0