springboot引入mvc
时间: 2025-06-01 12:03:58 浏览: 10
### 在Spring Boot中引入和配置MVC
在Spring Boot中,MVC功能的实现是通过Spring Web Starter依赖自动配置的。以下是如何正确引入和配置Spring MVC的方式。
#### 1. 引入Spring Web Starter依赖
在`pom.xml`文件中添加Spring Web Starter依赖以支持MVC功能[^1]。此依赖会自动引入所有必要的库来启用Spring MVC。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
#### 2. 创建控制器类
创建一个基于注解的控制器类,使用`@Controller`或`@RestController`注解标记该类。例如:
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot MVC!";
}
}
```
上述代码定义了一个简单的RESTful接口,当访问`/hello`路径时,将返回字符串"Hello, Spring Boot MVC!"[^2]。
#### 3. 配置静态资源
Spring Boot默认会从`src/main/resources/static`目录提供静态资源文件(如HTML、CSS、JavaScript等)。如果需要自定义静态资源位置,可以通过`application.properties`或`application.yml`文件进行配置[^3]。
**示例:`application.properties`**
```properties
spring.resources.static-locations=classpath:/custom-static/
```
#### 4. 自定义Spring MVC配置
如果需要对Spring MVC进行更多自定义配置,可以创建一个配置类并使用`@Configuration`和`WebMvcConfigurer`接口[^4]。
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
// 在这里添加自定义配置逻辑
}
```
#### 5. 启动应用程序
确保主类上标记了`@SpringBootApplication`注解,并且位于其他组件的父包中。运行主类中的`main`方法即可启动应用程序。
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
---
###
阅读全文
相关推荐



















