I have a doubt on spring DAO. Is this possible to use DAO without@repository annotations?if suppose I am not using @repository what will happen?
3 Answers
@Repository annotation causes a class to be instantiated by component scan as spring bean. If you delete this and do not create this bean other way (xml configuration, Java config, factory bean, etc.) you cannot inject this into other beans and cannot have injected beans into it, so you will have to create it and manage dependencies manually.

- 856
- 5
- 13
TL;DR: the value of @Respository
is for automatic exception translation.
When working with repositories (like databases), different systems may throw different exceptions that actually mean the same thing.
For example, when there's a unique ID conflict, Postgres might throw a PSQLException while MySQL may throw a MySQLIntegrityConstraintViolationException. If you have to support different databases (maybe including NoSQL ones) then handling all the possible vendor-specific exception types can be painful.
In addition to being a @Component
, the @Repository
annotation tells Spring to map / translate all of these low-level exceptions into a one unified DataAccessException
hierarchy, which is a runtime exception. Now we can simply code to DataAccessException
and not worry about the vendor-specific exceptions.
How useful is the @Repository
exception translation? Well, that depends on the application. If you don't have to support different underlying data stores, or use an ORM like Hibernate which already provides exception translation, then @Repository
doesn't add much. But if nothing else, the annotation serves as good documentation to mark the component's role as a repository in the application's architecture.

- 1,885
- 13
- 11
If you mark/initialize a DAO class like any other bean (annotate with @Component/@Service etc OR instantiate via @Bean) it will work, but you will lose the Spring feature specific to Repository (One such feature is Spring wrapping database specific Exception with DataAccessException).
Repository annotation is a marker annotation, which is used by Spring to make it available for Component scan as well as to enable extra Aspects w.r.t Data Access Layer. From below source code, you can see, purpose @Component.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
Here is a very nice article https://stackoverflow.com/a/38549461/7321990

- 21
- 3