首页 > 解决方案 > 如何在 Spring Boot 中使用抽象类?

问题描述

@Component
public abstract class AbstractProcessTask implements Task {

  @Resource
  protected WorkOrderEventService workOrderEventService;
  @Resource
  protected NodeService nodeService;
  @Resource
  protected ConfigReader configReader;

  protected void updateStatus(WorkOrderEvent workOrderEvent, String status, String description) {
    workOrderEvent.setStatus(status);
    workOrderEvent.setComments(description);
    workOrderEventService.saveWorkOrderEvent(workOrderEvent);
  }
}

我写了一个抽象类来使用,但是不知道怎么用。在旧的 spring 版本中,我们可以在 xml 中编写 abstract="true"。例如:

<bean id="BaseEventAction" class="com.sinosig.evaluation.fcff.web.event.BasicEventAction"
        abstract="true" parent="BaseAction">
        <property name="rowFactory" ref="FcffCacheAdapter" />
        <property name="caculate" ref="CaculateService" />
        <property name="diffusion" ref="DeffusionService" />
    </bean>

我该怎么办?

标签: javaspringspring-boot

解决方案


使用@Component抽象类不会帮助 Spring 从中创建一个 bean(当然,你知道,你不能从抽象类实例化一个对象)。在具体类上使用@Component注释。

@Component
public class MyProcessTask extends AbstractProcessTask {
...
}

其余的都很好。如果 spring 在扫描路径中找到具体的类,则会自动创建关联的 bean。

不要与属性“abstract=true”混淆

当您abstract=true在 bean 声明中提及属性时,您只是在抽象 bean。Spring 中的抽象 bean 与抽象类有些不同。事实上,Spring 中的抽象 bean 甚至不必映射到任何类。

看到这个不错的答案更多关于什么是抽象=“真”在春天?


推荐阅读