Using @Service Annotation in Spring Boot: A Detailed Guide

2 min read

Using @Service Annotation in Spring Boot: A Detailed Guide

The @Service annotation in Spring Boot is one of the core stereotype annotations used to define business logic in a Spring application. It is a specialized form of the @Component annotation and is used to mark a class as a service provider.

In this article, we will dive deep into what @Service is, how it works, and how you can use it effectively in your Spring Boot applications.


What Is @Service?

The @Service annotation is used to indicate that a class is holding the business logic. Spring will autodetect these classes through classpath scanning and register them as Spring Beans in the application context.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    String value() default "";
}

As you can see above, @Service is a meta-annotation built on top of @Component, which means it has the same behavior but is semantically clearer for service-layer logic.


Why Use @Service?

Using @Service has several benefits:

  • Makes your code more readable and well-structured.
  • Helps Spring manage business logic as beans.
  • Supports AOP (Aspect-Oriented Programming) features like transaction management and logging.

When to Use It?

Use @Service when your class contains business logic — for example, calculations, decision-making, data processing, or coordination between repositories and other services.


A Full Example: Spring Boot Service Layer

Let’s walk through an example application that manages a list of users.

1. Project Structure

com.example.userservice
├── controller
│   └── UserController.java
├── model
│   └── User.java
├── repository
│   └── UserRepository.java
├── service
│   └── UserService.java
└── Application.java

2. User Model

package com.example.userservice.model;

public class User {
    private Long id;
    private String name;

    // Constructors
    public User() {}

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and Setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

3. User Repository (Mock)

package com.example.userservice.repository;

import com.example.userservice.model.User;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class UserRepository {
    private final Map<Long, User> database = new HashMap<>();

    public List<User> findAll() {
        return new ArrayList<>(database.values());
    }

    public void save(User user) {
        database.put(user.getId(), user);
    }
}

4. User Service with @Service

package com.example.userservice.service;

import com.example.userservice.model.User;
import com.example.userservice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired  // Constructor Injection
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public void createUser(User user) {
        userRepository.save(user);
    }
}

5. User Controller

package com.example.userservice.controller;

import com.example.userservice.model.User;
import com.example.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getUsers() {
        return userService.getAllUsers();
    }

    @PostMapping
    public String addUser(@RequestBody User user) {
        userService.createUser(user);
        return "User added successfully";
    }
}

Summary

  • @Service is used to annotate service classes that contain business logic.
  • It makes the application easier to manage and test.
  • Together with @Repository and @Controller, it forms the foundation of a clean, layered architecture in Spring Boot.

🤞 Never miss a story from us, get weekly updates to your inbox!

Leave a Reply

Your email address will not be published. Required fields are marked *