1

I wanted to know if i could use the same spring crudRepository and Services interface with multiple classes by attributing a generic type to both of them in order to avoid rewriting the same thing over and over.

i'll try to explain this idea better with an example;

imagine if we had two different classes "Dog" and "Cat"

public class Dog extends Serializable{ //attributes here... }
public class Cat extends Serializable{ //attributes here... }

the service interface will more likely look like this :

public interface Services<T> {
List<T> getAllRecords();
T getRecordById(int id);
T insertRecord(T animal);
// etc
}

and the repository will be like this :

public interface GenericRepository<T>  extends CrudRepository<T,Serializable>{ //....}

then we'll be able to implement the services such as this :

@Service
public class CatServiceImpl implements Services<Cat>
{
@Autowired 
GenericRepository<Cat> repositoryCat;
//...
}

@Service
public class DogServiceImpl implements Services<Dog>
{
@Autowired 
GenericRepository<Dog> repositoryDog;
//...
}

and so on.. the problem is in the controller how can the @AutoWired annotation differentiate between the implementations? Any suggestions?

  • imho if you can create a crud based service you are doing it wrong. – M. Deinum Feb 20 '18 at 14:52
  • can show me the wae? @M – Yassine Ben Hamida Feb 20 '18 at 14:54
  • Did you get errors with `@Service` annotated classes ? Spring can autowire generic classes without `@Qualifier` since version 4. The relevant spring [blog post](https://spring.io/blog/2013/12/03/spring-framework-4-0-and-java-generics) – Manos Nikolaidis Feb 20 '18 at 14:59
  • Trying to do something similar here myself. I have 18 repository classes and 18 services. They all differ by the entity type. Surely there is a way to have a generic repo and a service to reduce number of classes and duplication of code. – Micho Rizo Jun 01 '18 at 21:18
  • Yeah i have tried implementing it with all my classes but failed lol, i used this generic repos with some generic classes that have simple crud operations (get, add, delete update, getall), then created repositories and services implementations for classes that have specific queries and operations. i use the @Qualifier annotation such as this `@Autowired @Qualifier("exempleServiceImpl") private Services implexemple;` – Yassine Ben Hamida Jun 06 '18 at 10:05

0 Answers0