Spring 可以在抽象类中自动装配吗? [英] Spring can you autowire inside an abstract class?

查看:75
本文介绍了Spring 可以在抽象类中自动装配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring 无法自动装配我的对象?是否可以在抽象类中自动装配对象.假设所有模式都在 application-context.xml

Spring is failing to autowire my object? Is it possible to autowire an object within an abstract class. Assume all schemas are supplied in application-context.xml

问题:在基类和扩展类(如果有)@Service @Component 上应该使用什么注解?

Question: What annotation should be on the base and extending classes (if any) @Service @Component?

示例

abstract class SuperMan {

    @Autowire
    private DatabaseService databaseService;

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}

拓展课程

public class SuperGirl extends SuperMan {

    @Override
    public void Fly() {
        //busy code
    }

    public doSomethingSuperGirlDoes() {

        //busy code

        doSuperPowerAction(thing)

    }

application-context.xml

<context:component-scan base-package="com.baseLocation" />
<context:annotation-config/>

推荐答案

通常情况下,Spring 应该进行自动装配,只要您的抽象类在为组件扫描提供的基础包中即可.

Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.

参见这个this 以供进一步参考.

See this and this for further reference.

@Service@Component 都是在 Spring 容器内创建注释类型 bean 的构造型.正如 Spring Docs 所述,

@Service and @Component are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,

这个注解作为@Component的特化,允许通过类路径扫描自动检测实现类.

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

这篇关于Spring 可以在抽象类中自动装配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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