Injecting an abstract class in config file instead of instantiating with a new calss which extents it Spring Boot

71 Views Asked by At

I am new to the spring boot and Bean concept. My Classes are as follow:

public class PersonController {
  private final AuditService<Person> auditService;
  
  @GetMapping("/{id}/revisions")
  public void getHistory(
    @PathVariable String id) {
    log.info("Get Audit history for entry with id: {}", id);
    List<AuditEntry<Person>> auditEntryList = auditService.getEntityRevisions(id);
    log.debug("Profile Audit history for id: {} is : {}", id, auditEntryList);

  }
}

@RequiredArgsConstructor
public abstract class AuditBaseService<E> implements AuditService<E> { ... }

I get an error in controller class where I defined the auditService, saying: "Could not autowire. No beans of 'AuditService' type found"`. Then I could fix this by adding a new class who could extend the AuditBaseService as below:

@Service
public class PersonAuditService extends AuditBaseService<Person> {

  public PersonAuditService(AuditReader pAudit) {
    super(pAudit);
  }

}

And the problem could solve. But this is not the good solution because the new class(PersonAuditService) does nothing except calls the superclass.

I would like to add creating bean inside the config file of the project. But I can not do it because I am still confused about bean's creation.

Would be great to get your supports. Thanks

2

There are 2 best solutions below

2
minus On

PersonAuditService is a class that could be injected into AuditService<Person> auditService.

AuditBaseService is an abstract class, you can't do new AuditBaseService(...), you must subclass AuditBaseService.

Spring can't create an instance of an abstract class.

0
Maryam Koulaei On

I guess I found my answer. But I am still not sure if this is a good way of creating bean and how it really works. It would be great if someone could explain it to me.

All I did was to define the personAuditService as a method inside the config file instead of creating extra class PersonAuditService which does the same for me.

config.java

@Bean
  public AuditBaseService<Person> personAuditService(AuditReader pAudit) {
    return new AuditBaseService<>(pAudit) {
    };
  }