17

I have encountered a strange problem. I am under the impression that component scan scans the sub packages recursively if a top level package is specified for scanning.

My repositories and entities are the maven dependency of the project. They live under the package name com.foo.bar.xyz and my application config is under package com.foo.bar. When I write @ComponentScan(basePackages = "com.foo.bar"), along with @EnableJpaRepositoriesit gives an error that repository bean not found.

However when I specify a top level repository package like @EnableJpaRepositories(basePackages = com.foo.bar.xyz) , along with component scan as above, it detects the repository just fine.

Now is this happening only because the repositories and entities are being injected as maven dependency? So does the recursive part of component scan, scans the sub packages or the subdirectories?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Nikhil Sahu
  • 2,463
  • 2
  • 32
  • 48
  • FYI, I made it work my specifically mentioning the packages to scan inside the `@EnableJpaRepositories` annotation – Nikhil Sahu Nov 30 '18 at 08:49

1 Answers1

15

Now is this happening only because the repositories and entities are being injected as maven dependency?

  • No it is not

So does the recursive part of component scan, scans the sub packages or the subdirectories?

  • Yes component scan does search recursively in sub packages

To elaborate here @ComponentScan is intended to search all classes having @Component or its sub types like @Controller whereas to enable Spring Data JPA by annotating the PersistenceContext class with the @EnableJpaRepositories annotation and to configure the base packages that are scanned when Spring Data JPA creates implementations for the repository interfaces. Hence the need for declaring the base package information for both @ComponentScan and @EnableJpaRepositories

Mudassar
  • 3,135
  • 17
  • 22