Spring Annotations and Annotation Based Dependency Injection

Posted By : Pulkit Gupta | 27-Apr-2018

In order to setup context regarding spring annotation, let me first choose the @Component annotation.

@Component- It is a stereotype which is generic and indicates that the class on which it is applied is spring component. These components are managed by Spring itself.

The listing below some key points regarding @Component.

  • <bean> is equivalent to @Component in Spring.
  • Controller basically performs the operation like calling the method in the service layer, dispatching, forwarding etc.

Now let’s discuss regarding those three annotations which separate “Layers” of an application. These annotations are specialized case annotation of component annotation

  1. @Repository -  It’s a stereotype for persistence layer, these are basically Dao which directly accessed by the database.
  2. @Service – It’s a stereotype for persistence layer, these basically keep business logic and calculation part of the application
  3. @Controller - Controller basically perform the operation like calling the method in the service layer, dispatching, forwarding etc.          

 

How Spring detects and performs dependency injection?

Basically, spring provides feature <context:component-scan> and which does annotation-driven dependency injection. It just automatically picks up the class annotated with @Component and registers it as a bean. So, it saved from the overhead of specifying the bean into the XML file.

But this tag only scans Component and no other annotations @service, @Controller and @Repository. These annotations are scanned because they are themselves annotated with annotation Component. Please look annotation definition of these components.

 

@Component
public @interface Service {
….
}

NOTE:-  @Component + other special functionality = {@Controller, @Service, @Repository}

That mean Controller, Service, and Repository are functionally the same.

 

So, with respect to scan auto detection and dependency injection for all these annotations are same. They all can be replaced with one in place and still it will work.

Even though choosing between annotation @service or @Component for service layer, the annotation @service is a better choice for obvious reasons.

Also, we have another annotation @ScheduledJob à So classes annotated with @ScheduledJob are spring beans and they are registered as quartz jobs

About Author

Author Image
Pulkit Gupta

Pulkit is software developer having key skills in Java/J2ee application. He has quite well hand-full skill in AngularJS and related technologies. He like to enjoy his work as much as he can and loves playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..