Difference between @Component, @Service, @Repository and @Controller annotations
Spring provides four different types of auto component scan annotations, they are @Component, @Service, @Repository and @Controller.
Technically, there is no difference between them, but every auto component scan annotation should be used for a special purpose and with in
the defined layer. Here is the purpose of each annotation
@Component: It is a basic auto component scan annotation, it indicates annotated class is a auto scan component.
@Repository: You need to use this annotation with in the persistance layer, which acts like database repository.
@Service: It indicates annotated class is a Service component in the business layer.
@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.
As above said, technically there is no difference between them, all of the 3 annotations @Service, @Repository and @Controller
implementations are annotated by @Controller annotation. So technically you can use @Controller for any auto component scan, but for better
readability and better standards use respective annotations. Look at the @Service annotation source code:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
String value() default "";
}
|
Here is the xml based configuration, you must register for auto component scan using component-scan tag.
<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.java2novice" />
</beans>
|
|