Spring可以在抽象类中自动装配吗?

sta*_*low 57 spring abstract-class autowired

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

问题:基础和扩展类(如果有)@Service @Component应该是什么注释?

abstract class SuperMan {

    @Autowire
    private DatabaseService databaseService;

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}
Run Code Online (Sandbox Code Playgroud)

扩展课程

public class SuperGirl extends SuperMan {

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

    public doSomethingSuperGirlDoes() {

        //busy code

        doSuperPowerAction(thing)

    }
Run Code Online (Sandbox Code Playgroud)

应用程序的context.xml

<context:component-scan base-package="com.baseLocation" />
<context:annotation-config/>
Run Code Online (Sandbox Code Playgroud)

Fre*_*ose 36

我有那种弹簧设置工作

带有自动装配字段的抽象类

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;
Run Code Online (Sandbox Code Playgroud)

以及使用@Component注释定义的几个子项.

  • 如果`settingsService`设置为`protected`,那么子类可以使用吗? (2认同)

And*_*san 31

通常,Spring应该进行自动装配,只要您的抽象类位于为组件扫描提供的基础包中.

这个这个以备将来参考.

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

此注释用作@Component的特化,允许通过类路径扫描自动检测实现类.


Muh*_*gan 5

如果你需要任何数据库操作,SuperGirl你会再次将它注入到SuperGirl.

我认为主要思想是在不同的类中使用相同的对象引用。那么这个呢:

//There is no annotation about Spring in the abstract part.
abstract class SuperMan {


    private final DatabaseService databaseService;

    public SuperMan(DatabaseService databaseService) {
     this.databaseService = databaseService;
    }

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}
Run Code Online (Sandbox Code Playgroud)
@Component
public class SuperGirl extends SuperMan {

private final DatabaseService databaseService;

@Autowired
public SuperGirl (DatabaseService databaseService) {
     super(databaseService);
     this.databaseService = databaseService;
    }

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

public doSomethingSuperGirlDoes() {

    //busy code

    doSuperPowerAction(thing)

}
Run Code Online (Sandbox Code Playgroud)

在我看来,注入一次到处运行:)