Search code examples
spring-bootspring-mvccontrollerrepository

Spring boot - multiple controllers with one repository


Can I make one repository and have multiple controllers using it? Im trying to autowire the repo with the class I want it to use. This is the base repository:

public interface BaseRepository <T> extends CrudRepository<T, Long> {

}

And here is how I want to use it:

@Autowired
    BaseRepository<Framework> repository;

I tried doing it in a way described above but im getting this error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'frameworkController': Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'baseRepository' defined in mas.Repositories.BaseRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class java.lang.Object
    
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseRepository' defined in mas.Repositories.BaseRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class java.lang.Object
    
Process finished with exit code 1


Solution

  • Im not sure your code snippet reflect what you really did but you should define the entity for which this repository is intended to work:

    public interface BaseRepository<Framework> extends CrudRepository<Framework, Long> {
    ...
    }
    

    And you can inject it without the type it's not necessary:

    @Autowired
    BaseRepository baseRepository;
    

    And yes you can definitively have multiple controllers for a single repository even if a better way to architecture your solution would be to have Services between your controllers layer and your repositories layers : https://tom-collings.medium.com/controller-service-repository-16e29a4684e5