spring @value returns null

守給你的承諾、 提交于 2019-12-12 03:44:44

问题


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?

来源:https://stackoverflow.com/questions/37493304/spring-value-returns-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!