Integrating Spring Boot with Spring MVC

Integrating Spring Boot with Spring MVC

In modern Java web development, deeply integrating the lightweight framework Spring Boot with the traditional core control layer Spring MVC is the preferred solution for building efficient, maintainable, and easy-to-deploy microservice architectures. Spring Boot simplifies environment setup through auto-configuration and starter dependencies, while Spring MVC provides a mature request handling mechanism. This article introduces a complete integration case, demonstrating how to build a RESTful API from scratch based on these two frameworks, covering the entire process from project initialization to core controller implementation.
First, we need to create a standard Maven multi-module or single-module project structure. To keep the code clear, we adopt a single module mode to demonstrate the simplest integration path. In the pom.xml file at the root of the project, besides the basic Spring Boot Starter Web and Spring MVC (usually included in the starter), it is recommended to introduce Lombok to reduce boilerplate code, as well as MapStruct or Jackson Annotations for object mapping and serialization.

<dependencies>
    <!-- Spring Boot Starter Web (includes Spring MVC) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Lombok to simplify entity and controller code -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- Spring Boot Starter Test (for integration testing) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2. Configure Application Startup and Global Exception Handling

The application.properties or application.yml file in Spring Boot serves as the bridge connecting the two frameworks. We need to ensure that Spring MVC configuration is correctly loaded and define a unified global exception handler to enhance system robustness. In src/main/java/com/example/demo/DemoApplication.java, simply keeping the standard @SpringBootApplication annotation will automatically complete the configuration registration.

Additionally, create a global ExceptionController (or a custom class inheriting ControllerAdvice) to handle exceptions in business logic, avoiding the need for every controller to repeatedly write try-catch blocks. This demonstrates Spring MVC's powerful capabilities in interceptors and response encapsulation.

3. Define Data Models and DTOs

Clear domain modeling is the foundation of API design. We use simple Java Beans (paired with Lombok) to represent backend data structures. Note the distinction between Entity classes (corresponding to database tables) and Data Transfer Objects (DTOs), which are used solely for network transmission and do not contain sensitive information or persistence logic.

// User.java (Simulated Entity)
public class User {
    private Long id;
    private String username;
    // Getter and Setter automatically generated by Lombok @Data
    
    public static void main(String[] args) {} 
}

4. Implement Spring MVC Controller Logic

This is the core phase. We need to create a RESTful-style controller, utilizing Spring Boot's @RestController annotation to replace the traditional @Controller + @ResponseBody combination, and paired with mapping methods like @GetMapping, @PostMapping to define interface paths. Spring Boot will automatically serialize returned objects to JSON (defaulting to Jackson) without requiring additional configuration.

@RestController
@RequestMapping("/api/users") // RESTful URL: GET /users, POST /users/{id}
public class UserController {

    @Autowired
    private UserRepository userRepository; // Assume DAO is already injected

    /**
     * Get all users list (GET)
     */
    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    /**
     * Create new user (POST)
     */
    @PostMapping
    public User createUser(@RequestBody User userDTO) {
        // Spring MVC automatically deserializes JSON Body to DTO, here directly saved to DB
        return userRepository.save(user); 
    }

    /**
     * Get user details by ID (GET by Id)
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

5. Run and Test Verification

After building, start the application. Spring Boot will automatically configure the Tomcat container and listen on a port (default is 8080). At this point, you can access the interfaces for testing via a browser or Postman, Swagger UI (if enabled):

  • GET http://localhost:8080/api/users will return a user list in JSON format;
  • POST http://localhost:8080/api/users?username=alice&password=secret can create a new record.

The entire process demonstrates how Spring Boot shields developers from the tediousness of underlying XML configuration or complex Bean definitions, allowing them to focus on business logic itself. The annotation-driven characteristics of Spring MVC are perfectly utilized in this process, making the code possess both high cohesion typical of frameworks and excellent development efficiency. This integration pattern is not only suitable for monolithic applications but also serves as a standard practice path for building microservice gateways and core APIs.