Search code examples
javaspringspring-bootspring-annotations

Why EntityScan , EnableJpaRepositories annotations required if we are already using componentScan annotation?


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.


Solution

  • 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.