This is a class-level annotation that is a specialization of @Component
designed to handle business logic. It will turn your class into a Spring-managed bean.
Why is it important?
By using this annotation, you are implementing a separation of concerns by placing the business logic in a specific layer, thereby improving code readability.
How to use it?
First, define a class annotated with @Service
that has some business logic in the methods:
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public String getWelcomeMessage(String username) {
return "Welcome, " + username + "!";
}
}
Then inject your created service where it’s needed:
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{username}")
public String welcomeUser(@PathVariable String username) {
return userService.getWelcomeMessage(username);
}
}
Let’s test it
Let’s call our endpoint
curl http://localhost:8080/users/SpringMastery
The result should look like this:
Welcome, SpringMastery!
Conclusion
That’s it, it's that easy to create a service in your application. Now you know how, when to use, and how important this annotation is in your Spring applications.
Have you ever thought about the difference between @Service
and @Component
?
Top comments (0)