what are @Repository and @Autowired used for. (Spring) what are @Repository and @Autowired used for. (Spring) spring spring

what are @Repository and @Autowired used for. (Spring)


@Repository is an annotation that marks the specific class as a Data Access Object, thus clarifying it's role. Other markers of the same category are @Service and @Controller

@Autowired is an annotation with a completely different meaning: it basically tells the DI container to inject a dependency. More info at http://apollo89.com/java/spring-framework-2.5.3/api/org/springframework/beans/factory/annotation/Autowired.html
EditMore info at tutorialpoint
or docs.spring.io


Both the annotations have different purposes to be used.

@Autowired: This is same as <bean="xyz" autowire="byType"> you define in the configuration file. The reference variable (dependency) that is annotated with @Autowired, will be injected by Spring container as any matching @Bean found in @Configuration class.
Plus the classes annotated with @Component, @Service, @Repository are too considered as beans so their objects are injected into the matching dependencies. Spring container scans the beans in the classes you mentioned for "component-scan" or @ComponentScan("xyz").

@Repository: This is also a spring-framework's annotation. When you annotate a class @Repository, spring container understands it's a DAO class and translates all unchecked exceptions (thrown from DAO methods) into Spring DataAccessException.DAO class is the class where you write methods to perform operations over db.


@Autowired and @Repository are very 2 different concepts.1.@ Repository: This define a class to be a repository, In general term you can use simply @Component but to define specifically, there are 3 more annotations like Controller,service and repository.Mainly 2 advantages: 1.If you have defined(context:component-scan)in servlet.xml to scan the defined package and find its own by spring. 2. More advantages you get from spring like database access error translation, so it is mainly defined to use with class in which you are connecting with database either with hibernate or jdbc.

@Autowired: to inject dependency at run-time by spring, means in a class, autowire a object ,and use it ,so this bean will automatically be made without defining in xml file