Search code examples
javaspring-batchhexagonal-architecture

How to add an Interface into a constructor in an ItemProcessor with SpringBatch


In my java project I use the hexagonal architecture. I have an Interface "Use Case" called RapprochementUseCase who is implemented by a Service called "RapprochementService".

In my ItemProcessor of my spring batch step I need to call to my Interface "RapprochementUseCase", so in my Processor I put in my constructor the interface thank's to the annotation RequiredArgsConstructor. But I got an error when I try to put the Interface into the parameter of my Processor.

I don't see in the documentation how to do this.. Do you have any ideas ?

In my declaration of processor :

  @Bean
  public ItemProcessor<PlaqueSousSurveillanceEntity, PlaqueLueEntity> rapprochementProcessor() {
    return new RapprochementProcessor(); <-- Error here
  }

RapprochementProcessor :

@Slf4j
@RequiredArgsConstructor
public class RapprochementProcessor implements ItemProcessor<PlaqueSousSurveillanceEntity, PlaqueLueEntity> {

  private final RapprochementUseCase rapprochementUseCase;


  @Override
  public PlaqueLueEntity process(PlaqueSousSurveillanceEntity item) {
    log.trace("Traitement d'une entrée PlaqueSousSurveillanceEntity: {}", item);

    List<PlaqueLue> plaqueLues = this.rapprochementUseCase.findRapprochementByPlaque(item.getPlaque());
    return new PlaqueLueEntity();
  }
}

When I tried to put the RapprochementUseCase in the contructor of the BatchConfiguration and if I declare the bean like :

  @Bean
  public RapprochementUseCase rapprochementUseCase(RapprochementUseCase rapprochementUseCase) {
    return rapprochementUseCase;
  }

I got an error : The dependencies of some of the beans in the application context form a cycle:


Solution

  • Your RapprochementProcessor requires a RapprochementUseCase, you should have a constructor generated by @RequiredArgsConstructor.

    You need to declare a bean of type RapprochementUseCase, and then pass it to your item processor like follows for example:

    @Bean
    public ItemProcessor<PlaqueSousSurveillanceEntity, PlaqueLueEntity> rapprochementProcessor(RapprochementUseCase rapprochementUseCase) {
        return new RapprochementProcessor(rapprochementUseCase);
    }