Oct 15, 2015

Spring | @Component, @Service, @Repository and @Controller

Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework. For all these annotations (stereotypes), technically the core purpose is same. Spring automatically scans and identifies all these classes that are annotated with “@Component, @Service, @Repository, @Controller” and registers BeanDefinition with ApplicationContext. 

Spring Configuration for Component-scan
For these beans to be instantiated by Spring, we need to have the following configuration in the spring configuration XML.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     <context:component-scan base-package="com.java.spring"/>
 </beans>
@Component, @Repository, @Service and @Controller annotations
1) The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. It is generic and can be used across application. To use this annotation, apply it over class as below:

@Component
public class EmployeeDAOImpl implements EmployeeDAO {
    ...
}
2) @Repository annotation is a specialization of the@Component, annotate classes at persistence layer, which will act as database repository. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

3) The @Service annotation is also a specialization of the component annotation. It’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behaviour might rely on it in the future.

4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked with it are automatically imported into the DI container.


Hope you liked the article. Subscribe at +Java Territory to stay updated.


0 comments:

Post a Comment