简体   繁体   English

如何在Spring Boot中使用抽象类?

[英]How to use abstract classes in 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);
  }
}

I write a abstract class for use,But I don't know how to use. 我写了一个抽象类供使用,但我不知道如何使用。 At Old spring version,We can write abstract="true" in xml. 在旧的春季版本中,我们可以在xml中编写abstract =“ true”。 for example: 例如:

<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>

what should I do? 我该怎么办?

Using @Component over an abstract class would not help Spring to create a bean from that (As of course, you know, you can not instantiate an object from an abstract class). 在抽象类上使用@Component不会帮助Spring从该类创建Bean(当然,您知道不能从抽象类实例化对象)。 Use @Component annotation over the concrete classes. 在具体类上使用@Component批注。

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

And the rest are okay. 其余的都还可以。 If spring finds the concrete classes in the scan path, the associated beans will be created automatically. 如果spring在扫描路径中找到具体的类,则将自动创建关联的bean。

Don't confuse with attribute 'abstract=true' 不要与属性“ abstract = true”混淆

When you mention the attribute abstract=true in a bean declaration, you are just abstracting the bean. 当您在bean声明中提到属性abstract=true时,您只是在抽象bean。 Abstract beans in Spring are somewhat different from abstract classes. Spring中的抽象bean与抽象类有所不同。 In fact, the abstract bean in Spring doesn't even have to be mapped to any class. 实际上,Spring中的抽象bean甚至不必映射到任何类。

See this nice answer for more about What is meant by abstract=“true” in spring? 有关更多信息,请参见这个不错的答案

You can simply extend the abstract class with another class, and use @Component in the subclass. 您可以简单地用另一个类扩展抽象类,并在子@Component中使用@Component You may also need to implement any methods in the superclass. 您可能还需要实现超类中的任何方法。

@Component
public class AbstractChild extends AbstractProcessTask {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM