簡體   English   中英

在超類中帶有@Autowired的Spring工廠bean

[英]Spring factory bean with @Autowired in superclass

我在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>

抽象類FactoryBean protected ConfigBean configBean屬性不是@Autowired ,因此為null ,並且構造方法拋出NullPointerException 如果我將其放在每個子類中,它可以正常工作,但是會重復代碼。 有辦法解決這個問題還是我做錯了什么?

把自己放在春天的鞋子里。 它必須實例化FactoryBean ,然后初始化其configBean字段。 因此,它要做的第一件事就是調用構造函數。 然后,一旦對象存在,它將初始化對象的字段。 如果對象尚不存在,則顯然無法初始化該字段。 因此,在調用構造函數時,該字段仍為null。

使用構造函數注入,或使用帶有witb @PostConstruct注釋的方法來調用configBean

就是說,您嘗試初始化的私有property字段未在任何地方使用,因此您也可以刪除它,也可以刪除configBean字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM