问题描述
我有一个项目,其中有一个接口,一个实现相同接口的Abstract类,然后是一组实现该接口并扩展Abstract类的具体类。
I have a project where I have an interface, an Abstract class implementing the same interface and then a set of concrete classes which implement this interface and extend the Abstract Class.
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文件具有对该组件的组件扫描。
Spring file has a component scan for the package.
<context:annotation-config>
<context:component-scan base-package="com.xyz" />
我正在使用工厂来获取 TypeAInvoice 发票
现在调用 invoice.process()
会在进入 write.write()
I am using a factory to get an instance of
TypeAInvoice
invoiceNow calling invoice.process()
gets a NPE when getting to write.write()
我不确定这里缺少什么。我试图查看组件的扫描和范围,但在概念上找不到任何错误。
I am not sure what am I missing here. I tried to see the component scan and scope and could not find anything conceptually wrong.
推荐答案
推荐答案
这取决于您工厂的工作方式,这可能是问题所在。如果工厂创建了新的
TypeAInvoice
,则弹簧接线不适用。您必须查询Bean的Spring上下文。一种方法(虽然不是很漂亮)是使用 ContextLoader
:
Depending on what your Factory does, this may be the problem. If the Factory creates a new
TypeAInvoice
, Spring wiring doesn't apply. You have to query the Spring context for the Bean. One way (though not very pretty) is to use ContextLoader
:
return ContextLoader.getCurrentWebApplicationContext().getBean(TypeAInvoice.class)
我说静态工厂和弹簧不要在一起很好。 Spring代表控制反转模式,而Factory代表服务定位器模式。我建议您摆脱工厂并自动装配Spring Bean。
I'd say static Factories and Spring don't go to well together. Spring stands for the Inversion of Control pattern, while Factories stand for the Service Locator pattern. I'd suggest that you get rid of your factories and autowire your Spring Beans.
这篇关于Spring自动装配不适用于抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!