Reputation: 347
I have created on springboot project where there is a JPA class :-
package com.example.demo.jpa;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Users;
@Repository
public interface AppRepo extends CrudRepository<Users, Integer>, AppRepoCustom {
public List<Users> findAllByJob(String job);
}
Another AppRepoCustom Interface is like this:
package com.example.demo.jpa;
import java.util.List;
public interface AppRepoCustom {
public List<String> getAllNames();
}
Implementation of the interface :-
package com.example.demo.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.example.demo.model.Users;
public class AppRepoCustomImpl implements AppRepoCustom {
@PersistenceContext
EntityManager entityManager;
@Override
public List<String> getAllNames() {
Query query = entityManager.createNativeQuery("SELECT name FROM springbootdb.Users as em ", Users.class);
return query.getResultList();
}
}
Now inside my controller class I am injecting the AppRepo object
@Autowired
AppRepo appRepo;
My question is I haven't specified anywhere that which implementation of AppRepo to be injected then how spring is able to inject it without any errors? When we create a object of type interface like Interface objectName = new implClass(); where implClass contains all the implementation of the interface methods.but in the above example some implementations are in are in CrudRepository class and some are in AppRepoCustom so How does this object creation works here? I am confused. How internally objects in being created when we create object like Interface objectName = new implClass();and in the given scenario.
Upvotes: 0
Views: 72
Reputation: 622
It will be ambiguous if you @Autowired AppRepoCustom
. But in your case you have @Autowired AppRepo
which is child of AppRepoCustom interface. So Spring knows you have asked to provide bean of child interface and provides it without error.
As far as which concrete implementation will be autowired in case of AppRepo
, See the following reference from spring documentation.
In this case we instruct Spring to scan com.acme.repositories and all its sub packages for interfaces extending Repository or one of its sub-interfaces. For each interface found it will register the persistence technology specific FactoryBean to create the according proxies that handle invocations of the query methods.
For further details read documentation.
Upvotes: 1
Reputation: 901
Spring boot application scans all classes with tags i.e. @repository, @Component, @Bean, @Controller etc and create objects. Also, in your case, you have @Autowired the class @Apprepo so there is no conflict, it should work perfectly fine.
Upvotes: 0