@Service Annotation in Spring

@Service annotation is a part of the Spring Framework and is used to mark a class as a service layer component. This annotation is typically used in conjunction with @Component, which is a general-purpose annotation for marking a class as a component in Spring.

To learn about other Spring Boot annotations check out Spring Stereotype Annotations tutorial.

How to Use @Service Annotation

@Service annotation can be used to denote a class that performs a specific service or function in a Spring Boot application. It is typically used to denote a class that performs business logic or data manipulation tasks.

To use @Service annotation in a Spring Boot Rest application with Maven, follow these steps:

Step 1. Add Spring Boot Web Dependency

Add the Spring Boot starter dependency in your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 2. Annotate Class with @Service Annotation

Create a class that performs a specific service or function in your application. For example, let’s say you want to create a class that sends notification messages. You can create a class called NotificationService:

@Service
public class NotificationService {

    public void sendNotification(Notification notification) {
        // Code to send notification message 
    }
}

Step 3. Inject Service Class into a Controller Class

Inject the DataService class into the component or controller that needs to use it. For example, if you want to use the DataService class in a controller, you can do the following:

@RestController
public class NotificationsController {

    @Autowired
    private NotificationService notificationService;

    @PostMapping("/notifications/send")
    public void sendNotification(@RequestBody Notification notification) {
        notificationService.sendNotification(notification);
    }
}

Ow you can run your Spring Boot application and make a request to the /notifications/send endpoint to trigger the NotificationService’s sendNotification() method.

Conclusion

@Service annotation is a useful tool for organizing and separating business logic and data manipulation tasks in a Spring Boot application. By using @Service annotation, you can clearly denote which classes in your application are responsible for performing specific services and functions.

To learn more, check out Spring Boot tutorials page.