we can declare repository classes in this way
public interface DepartmentRepository extends JpaRepository<Department, Integer>
and this way
@Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer>
What is the difference between this two approach mentioned. Because if we remove the @Repository
annotation then the code will work fine then what is the difference, can anyone explain me on this.
While the other answers go into detail about the sterotype annotations they don't document why exactly its not needed, its a Spring Boot feature - not Spring Framework.
With Spring Boot, it will automatically scan child packages from the main SpringBootApplication class and detect repository interfaces and create beans for you with the use of Autoconfiguration that is part of the SpringBootApplication
Spring Data repositories usually extend from the Repository or CrudRepository interfaces. If you use auto-configuration, repositories are searched from the package containing your main configuration class (the one annotated with @EnableAutoConfiguration or @SpringBootApplication) down.
https://docs.spring.io/autorepo/docs/spring-boot/current/reference/htmlsingle/#boot-features-spring-data-jpa-repositories
If you were not using Spring Boot, or the repository was not in package, or child-package, of the Spring Boot Application it would need to be annotated and the package scanned, or a bean created.
Spring Data can create implementations of @Repository interfaces of various flavors. Spring Boot handles all of that for you, as long as those @Repositories are included in the same package (or a sub-package) of your @EnableAutoConfiguration class.
For many applications, all you need is to put the right Spring Data dependencies on your classpath. There is a spring-boot-starter-data-jpa for JPA, spring-boot-starter-data-mongodb for Mongodb, etc. To get started, create some repository interfaces to handle your @Entity objects.
Spring Boot tries to guess the location of your @Repository definitions, based on the @EnableAutoConfiguration it finds. To get more control, use the @EnableJpaRepositories annotation (from Spring Data JPA).
See the documentation for more information on this behavior e.g. taking more control over the creation of repositories.
https://docs.spring.io/autorepo/docs/spring-boot/current/reference/htmlsingle/#howto-use-spring-data-repositories
@Repository
is a special type of @Component
and we annotate the interface which acts as a repository with @Repository
annotation. @Repository
deals with catching exceptions that are related to data persistence.
We don't need to use @Repository
annotation when we are extending JpaRepository
because Spring detects that the predefined JpaRepository
has been extended and recognises the interface that extends JpaRepository
as a repository.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With