java - 如何在 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>
我该怎么办?
解决方案
使用@Component
抽象类不会帮助 Spring 从中创建一个 bean(当然,你知道,你不能从抽象类实例化一个对象)。在具体类上使用@Component
注释。
@Component
public class MyProcessTask extends AbstractProcessTask {
...
}
其余的都很好。如果 spring 在扫描路径中找到具体的类,则会自动创建关联的 bean。
不要与属性“abstract=true”混淆
当您abstract=true
在 bean 声明中提及属性时,您只是在抽象 bean。Spring 中的抽象 bean 与抽象类有些不同。事实上,Spring 中的抽象 bean 甚至不必映射到任何类。
看到这个不错的答案更多关于什么是抽象=“真”在春天?
推荐阅读
- excel - 使用带有 SUMIFS 的 Combobox 来汇总满足要求的数据的用户表单
- python-3.x - 如何从后到前排列列表
- kotlin - 如何使用 Kleisli 访问调用链的每个函数中的上下文?
- java - ResultSet 异常 - 开始之前
- angular - 聊天应用程序中的 RXJs 退订问题
- html - 如何用 CSS Flexbox 搭建一个挂桌
- java - 发布构建应用程序崩溃导致 proguard 规则
- driver - 在 x86_64 上寻找 Coral M.2 加速器 + RHEL/Centos 8 驱动程序
- python - 如何使用其架构从 Pyspark 数据框创建配置单元表?
- php - 提交带有php错误的表单