使用spring factory-method

时间:2016-05-28 03:47:22

标签: java spring spring-mvc factory-method

这个问题是this one的后续行动。

问题是我想在.properties文件中注入一个值并始终返回null。原因是myClassContext正在调用new myclass1()和new myclass2(),因此myclass1和myclass2都不是由Spring管理的。

所以我现在的问题是如何重构代码以使@Value(“$ {path}”)有用,这样我就可以根据参数获得myClassContext.getPath(params)的正确结果。

我认为我应该使用静态工厂方法来做到这一点,但我想不出解决方案。

在我的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"/>
....

在abc.properties中:

path=testpath

我的班级:

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

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

myClassContext:

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

Spring管理实例的更好方法是什么,@ value将正确注入?

0 个答案:

没有答案