The @Service annotation is stereotype annotation which is used to create spring bean for the specified class. The stereotype annotation are the markers annotation which can be used for any class that fulfills the role in application. The spring application creates the bean for the class which now does not required to configure in the spring xml configuration file.
@Service annotation definition
1 @Target({ElementType.TYPE})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Component
5 public @interface Service {
6
7 }
Note: In the implementation, the service interface is annotated with @Component. Spring allows to use this annotation to create bean for the application but it is not a best practice for readability to create bean of service with Component annotation.
In spring, while bean is created using stereotype annotation, it creates bean Id by converting the first character of the class or component to lowercase, it is default behavior. ie ‘ExampleController’ to ‘exampleController’. Once the bean is created in the application, it can be retrieve from IOC container either using getBean() method by providing 'exampleService' or by specifying bean Id in @Qualifier annotation.
@Component annotation definition
1 @Target(ElementType.TYPE)
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Indexed
5 public @interface Component {
6
7 }
8
Example
Creating bean using @Service annotation
1 package com.iogyan.service;
2
3 import org.springframework.stereotype.Service;
4
5 @Service
6 public class ExampleService {
7
8 public String getValue() {
9 return "Example service getValue method called...";
10 }
11 }
In the above code, an ExampleService class is created by annotating with @Service stereotype annotation with method getValue() that returns string. When a configuration read the specified package, It creates Bean of class ExampleService that will be store in sprint container. As name of the spring bean ID is not specified, a default spring bean ID will be same as name of the class where first character of the bean ID will be in lowercase letter. ie. exampleService.
@Service stereotype with custom bean ID
Custom bean ID using @Service annotation
1 package com.iogyan.service;
2
3 import org.springframework.stereotype.Service;
4
5
6 @Service("expService")
7 public class ExampleService {
8
9 public String getValue() {
10 return "Example service getValue method called...";
11 }
12 }
In the above code, a ExampleService class is annotated with @Service annotation by specify custom bean ID, if the default one needs to be replace. When a class is scanned with spring, it creates bean of class with specified bean ID. It can be useful when class name consist of many words or sometime to avoid ambiguity.
Related options for your search