Spring Autowiring 不适用于抽象类 [英] Spring Autowiring not working for Abstract classes

查看:23
本文介绍了Spring Autowiring 不适用于抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中有一个接口,一个实现相同接口的抽象类,然后是一组实现该接口并扩展抽象类的具体类.

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 invoice Now 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 发票的实例

I am using a factory to get an instance of TypeAInvoice invoice

根据您的工厂做什么,这可能是问题所在.如果工厂创建了一个新的 TypeAInvoice,则 Spring 接线不适用.您必须查询 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 不能很好地结合在一起.Spring 代表控制反转模式,而工厂代表服务定位器模式.我建议您摆脱工厂并自动装配 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 Autowiring 不适用于抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆