car*_*ret 2 java inheritance spring 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());
}
}
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
protected ConfigBean configBean抽象类中的属性FactoryBean不存在@Autowired,因此null构造函数抛出一个NullPointerException.如果我把它放在每个子类中,它工作正常,但它是重复的代码.有办法解决这个问题,还是我做错了什么?
把自己放在春天的鞋子里.它必须实例化FactoryBean,然后初始化其configBean字段.所以,它要做的第一件事就是调用构造函数.然后,一旦对象存在,它将初始化对象的字段.如果对象尚不存在,显然无法初始化该字段.因此,在调用构造函数时,该字段仍为null.
使用构造函数注入,或使用带注释的witb方法@PostConstruct来调用configBean.
也就是说property,您尝试初始化的私有字段不会在任何地方使用,因此您也可以删除它,并删除该configBean字段.
| 归档时间: |
|
| 查看次数: |
3547 次 |
| 最近记录: |