gpt4 book ai didi

java - 父类(super class)中带有@Autowired的Spring工厂bean

转载 作者:行者123 更新时间:2023-11-30 06:13:58 29 4
gpt4 key购买 nike

我在 Spring 中实现了一个工厂 bean 来实例化父类(super class)的不同子类。我遇到的问题是父类(super class)属性不是 @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。如果我将它放在每个子类中,它工作正常,但它会是重复的代码。有没有办法解决这个问题,还是我做错了什么?

最佳答案

设身处地为 Spring 着想。它必须实例化 FactoryBean,然后初始化它的 configBean 字段。所以,它要做的第一件事就是调用构造函数。然后,一旦对象存在,它将初始化对象的字段。如果对象尚不存在,它显然无法初始化该字段。因此,在调用构造函数时,该字段仍然为空。

使用构造函数注入(inject),或者使用注解为@PostConstruct的方法来调用configBean

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

关于java - 父类(super class)中带有@Autowired的Spring工厂bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31087772/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com