我有一个项目,我有一个接口(interface),一个实现相同接口(interface)的抽象类,然后是一组实现这个接口(interface)并扩展抽象类的具体类。
public interface Invoice
{
void process();
}
@component
public abstract class AbstractInvoice(){
@Resource
protected Writer writer;
protected validateInvoice(){
//some implementation
}
}
@Component
public Class TypeAInvoice() extends AbstractInvoice implements Invoice{
@Override
public void process(){
//... some code
writer.write();
}
}
public Interface Writer(){
public void write();
}
@Component
public class CDWriter implements Writer{
@Override
public void write() { /* implementation.....*/}
}
Spring 文件对包进行了组件扫描。
<context:annotation-config>
<context:component-scan base-package="com.xyz" />
我正在使用工厂获取
TypeAInvoice
的实例发票现在调用
invoice.process()
到达 write.write()
时获得 NPE我不确定我在这里错过了什么。我试图查看组件扫描和范围,但在概念上找不到任何错误。
最佳答案
I am using a factory to get an instance of TypeAInvoice invoice
根据您的工厂所做的事情,这可能是问题所在。如果工厂创建一个新的
TypeAInvoice
, Spring 接线不适用。您必须查询 Bean 的 Spring 上下文。一种方法(虽然不是很漂亮)是使用 ContextLoader
:return ContextLoader.getCurrentWebApplicationContext().getBean(TypeAInvoice.class)
我会说静态工厂和 Spring 不能很好地结合在一起。 Spring 代表控制反转模式,而工厂代表服务定位器模式。我建议你摆脱你的工厂并 Autowiring 你的 Spring Bean。
关于Spring Autowiring 不适用于抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11273070/