DEV Community

Sudhakar V
Sudhakar V

Posted on

Spring Boot MVC (Model-View-Controller) architecture

In a Spring Boot MVC (Model-View-Controller) architecture, your application is divided into three main layers:


Image description

๐Ÿ” 1. Model

Represents the data and business logic of the application.

  • Typically includes:

    • Java classes (POJOs) representing the data.
    • Entities (annotated with @Entity).
    • Repository interfaces (usually extending JpaRepository or CrudRepository).

โœ… Example:

@Entity
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String email;
    // Getters and setters
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฎ 2. Controller

Handles HTTP requests and maps them to the correct service methods. It acts as the entry point for the web layer.

  • Annotated with @Controller or @RestController.
  • Uses annotations like @GetMapping, @PostMapping, etc.
  • Communicates with the service layer.

โœ… Example:

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

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

๐Ÿง  3. Service

Encapsulates business logic. Called by the controller and interacts with the repository (data access) layer.

โœ… Example:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List<User> getUsers() {
        return userRepository.findAll();
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ—ƒ๏ธ Repository

Handles database operations. Interfaces extend JpaRepository, CrudRepository, etc.

โœ… Example:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ–ผ๏ธ View (optional in RESTful APIs)

In traditional MVC, views (HTML pages, Thymeleaf, JSP) are returned to the user. For APIs, JSON is typically returned.

  • Views are placed in src/main/resources/templates/ (for Thymeleaf).
  • Use @Controller (not @RestController) when returning views.

โœ… Example (Thymeleaf View):

@Controller
public class PageController {
    @GetMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "home"; // maps to home.html
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงญ Spring Boot MVC Project Flow

Client (Browser / Postman)
      โ†“
Controller (handles HTTP requests)
      โ†“
Service (business logic)
      โ†“
Repository (database access)
      โ†“
Database (e.g., PostgreSQL)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)