9

I am already using ComponentScan annotation in Main class of Spring Boot app , but If I use only this annotation it will gives issue while getting repositories reference. So to overcome this I am using EntityScan and EnableJpaRepositories annotations with componentScan.

@EntityScan(basePackages={"com.gonkar.fleetms.models"})
@EnableJpaRepositories(basePackages={"com.gonkar.fleetms.repositories"})

So my question is why its required to use other two annotations? if I am already using @ComponentScan.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
OnkarG
  • 267
  • 1
  • 3
  • 16

1 Answers1

12

The @ComponentScan annotation is used to create beans for classes annotated with @Component, @Controller / @RestController, @Service, @Repository. It marks them for being added to the Spring container (making them eligible for dependency injection and allowing them to be @Autowired).

The @EntityScan annotation doesn't create any beans, it identifies which classes should be used by a JPA persistence context.

The @EnableJpaRepositories annotation is used to create repository classes from Spring Data interfaces.

All three annotation are often used together, but they are responsible for different things.

Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27
  • Thanks for detailed description , But I have observed if I use only componentScan annotation it will give issue for Autowire annotation for service and repository references. Correct me if I am wrong i.e. we must use compopnentScan , EntityScan , EnableJpaRepository together – OnkarG Oct 05 '20 at 07:57
  • If some of your beans are resolved by Spring using not XML / JavaConfig but annotations, then you have yo use `@ComponentScan`. If some of your repositories are Spring Data repositories, you need to use additionaly `@EnableJpaRepositories`. And if you have some JPA entities, it's needed to use `@EntityScan`. So - yes, they must be used together. – Alexandra Dudkina Oct 05 '20 at 08:08
  • But there are projects without persistence layer or using non-JPA persistence. In that cases there is no need to use both `@EntityScan` or `@EnableJpaRepositories`. Some works for projects using JPA but not using Spring Data - in such cases datasource, entity manager factory and transaction manager should be defined explicitly without those annotations. – Alexandra Dudkina Oct 05 '20 at 08:12
  • Okay , Thank you very much @Alexandra Dudkina – OnkarG Oct 05 '20 at 09:00