在超类

时间:2015-06-27 10:37:30

标签: java spring inheritance factory autowired

我在Spring中实现了一个工厂bean来实例化超类的不同子类。我遇到的问题是超类属性不是@Autowired(我猜是由于工厂方法中的new命令)。这是我的代码:

@Component
public class ConfigBeanImpl implements ConfigBean{

@Override
public String expandParam(String param) {
    return String.format("expanded %s", param);
}
}

public abstract class FactoryBean {

@Autowired
protected ConfigBean configBean;

private String property;

protected FactoryBean() {
    this.property = configBean.expandParam("property");
}

public abstract String getProperty();

public static FactoryBean GET(int id) {
    return new FactoryBeanGet(id);
}

public static FactoryBean POST(String param){
    return new FactoryBeanPost(param);
}
}

public class FactoryBeanGet extends FactoryBean {

private int id;

protected FactoryBeanGet(int id) {
    this.id = id;
}

@Override
public String getProperty() {
    return Integer.toString(id);
}
}

public class FactoryBeanPost extends FactoryBean {

private String param;

protected FactoryBeanPost(String param) {
    this.param = param;
}

@Override
public String getProperty() {
    return param;
}
}

public class Main {

public static void main(String[] args) {
    ApplicationContext context = 
               new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});

    FactoryBean bean = (FactoryBean) context.getBean("factoryBeanGet", 12);
    System.out.println(bean.getProperty());

    bean = (FactoryBean) context.getBean("factoryBeanPost", "test param");
    System.out.println(bean.getProperty());
}
}

applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="com.spring" />

<bean id="factoryBeanGet" scope="prototype" class="com.spring.bean.FactoryBean"
    factory-method="GET">
</bean>

<bean id="factoryBeanPost" scope="prototype" class="com.spring.bean.FactoryBean"
    factory-method="POST">
</bean>

抽象类protected ConfigBean configBean中的FactoryBean属性不是@Autowired,因此是null,构造函数抛出NullPointerException。如果我将它放在每个子类中,它可以正常工作,但它是重复的代码。有没有办法解决这个问题,或者我做错了什么?

1 个答案:

答案 0 :(得分:5)

把自己放在春天的鞋子里。它必须实例化FactoryBean,然后初始化其configBean字段。所以,它要做的第一件事就是调用构造函数。然后,一旦对象存在,它将初始化对象的字段。如果对象尚不存在,显然无法初始化该字段。因此,在调用构造函数时,该字段仍为空。

使用构造函数注入,或使用带注释的witb @PostConstruct方法调用configBean

也就是说,您尝试初始化的私有property字段不会在任何地方使用,因此您也可以删除它,并删除configBean字段。