jeudi 11 juillet 2019

How to Create Generic @Service That Injects Specific @Repository?

Our software have a specific behaviour that applies to all the functionalities, what change in mosts cases is the Entity used in operations, and for that we need specific implementation for @Repositoy layer.

So, we develop an "simple" architecture @RestController -> @Service -> @Repository with some generics, to work for all the functionality. Like this:

@RestController
@RequestMapping("test")
// This is specific implementation
public class DiariasApi implements DefaultApiInterface<DiariasDTO, DiariasDTOFilter, Integer> {

    @Autowired
    private DefaultService<DiariasDTO, DiariasDTOFilter, Integer> defaultService;

    @Override
    @GetMapping("/page")
    public Page<DiariasDTO> pageSearch(final DiariasDTOFilter filter) {
        return this.defaultService.pageSearch(filter);
    }

    @Override
    @GetMapping("/detail")
    public DiariasDTO detail(@PathVariable("key") final Integer key) {
        return this.defaultService.detail(key);
    }

}


@Service
// This is generic implementation
public class DefaultService<D extends Serializable, F extends Serializable, C> {

    @Autowired
    // The Problem is here.
   // Here I want the call to be the specific @Repository.
    private DefaultRepositoryInterface<D, F, C> defaultRepository;

    @Transactional(readOnly = true)
    public Page<D> pageSearch(final F filter) {
        return this.defaultRepository.pageSearch(filter);
    }

    @Transactional(readOnly = true)
    public D detail(final C key) {
        return this.defaultRepository.detail(key);
    }

}

@Repository
// This is specific implementation
public class DiariasRepository implements DefaultRepositoryInterface<DiariasDTO, DiariasDTOFilter, Integer> {

    @Override
    public Page<DiariasDTO> pageSearch(final DiariasFiltro filtro) {
        //some specific code;
    }

    @Override
    public Optional<DiariasDTO> detail(final Integer key) {
        //some specific code;
    }

We want to implement only the @RestController and the @Repository for each functionality, and let the @Service layer be only one generic bean that knows how to call the specific @Repository. But when we do that and have more than one implementation we receive the following error message, witch tells us the problem with @Autowired:

Description:
Field defaultRepository in package.DefaultService required a single bean, but 2 were found:
    - conveniosRepository: defined in file ...
    - diariasRepository: defined in file ...

We want the @Service layer to be unique, can we do that?

Aucun commentaire:

Enregistrer un commentaire