Reputation: 109
I have created a spring project which has a controller and all of its logic is written in Service Interface, which is implemented by ServiceImpl class. I have a repository with which has a model.
//Service Interface
public interface Service{
List<Model> getAllKpiData();
}
//ServiceImpl Class
@Service
public class ServiceImpl implements Service{
@Autowired
private KPIRepository kpiRepository;
@override
private List<Model> getAllKpiData()
{
this.kpiRepository.findAll();
//gets me an empty list.
}
}
//KPIRepository
@Repository
public interface KPIRepository extends MongoRepository<KPIModel, String>
{
}
//Another Service Interface in another package
public interface AnotherService{
List<Model> getAllKpiData();
}
//ServiceImpl Class
@Service
public class AnotherServiceImpl implements Service{
@Autowired
private KPIRepository kpiRepository;
@override
private List<Model> getAllKpiData()
{
this.kpiRepository.findAll();
//gets me list of values, which are inside the repo(master data).
}
}
Both of them are pointing to same repo, but in AnotherService class i am able to get values inside the repository, whereas i am not able to get any values inside Service, on doing this.kpiRepository.findAll().
Upvotes: 5
Views: 7503
Reputation: 6265
Do you have spring-boot-starter-data-mongodb
dependency on classpath? If yes, then is KPIRepository in the same package as your main class? If not then in your main class put this annotation @EnableMongoRepositories(basePackageClasses=KPIRepository.class)
to safely tell Spring Data MongoDB to scan a different root package by type if your project layout has multiple projects and its not finding your repositories. Or you can use @EnableMongoRepositories(basePackages = "com.acme.repositories.mongo")
to specify the package that contains all of your repositories.
The presense of spring-boot-starter-data-mongodb will automatically enable @EnableMongoRepositories
. And Spring will automatically create proxies of all classes implementing Repository<T,ID>
(your class implements MongoRepository, which itself implements Repository) and create beans of them and make them available for injection. And when your repository is in a different package then it is unable to create proxies for your repositories, hence fails to create beans for them. And since there are no beans, it cannot inject them, hence you see the error.
Upvotes: 11
Reputation: 689
Did you use the @EnableMongoRepositories annotation? Take a look to this link: https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html. Review the "6.2 usage" point.
Regards
Upvotes: 2