In a Spring Boot MVC (Model-View-Controller) architecture, your application is divided into three main layers:
๐ 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
orCrudRepository
).
โ
Example:
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
// Getters and setters
}
๐ฎ 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();
}
}
๐ง 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();
}
}
๐๏ธ Repository
Handles database operations. Interfaces extend JpaRepository
, CrudRepository
, etc.
โ
Example:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
๐ผ๏ธ 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
}
}
๐งญ Spring Boot MVC Project Flow
Client (Browser / Postman)
โ
Controller (handles HTTP requests)
โ
Service (business logic)
โ
Repository (database access)
โ
Database (e.g., PostgreSQL)
Top comments (0)