Springboot 怎么集成springmvc
时间: 2023-07-17 19:01:02 浏览: 68
在Spring Boot中,集成Spring MVC非常简单。以下是集成Spring MVC的步骤:
1. 添加依赖:在pom.xml文件中添加Spring MVC的依赖。可以使用Spring Boot的起步依赖来简化配置,如下所示:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. 创建控制器:在项目中创建一个控制器类,使用`@RestController`或`@Controller`注解进行标记,并添加相应的请求映射方法。
```java
@RestController
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "Hello Spring MVC!";
}
}
```
3. 启动应用程序:在主类中添加`@SpringBootApplication`注解,并使用`SpringApplication.run()`方法启动应用程序。
```java
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
```
4. 配置相关项(可选):如果需要自定义一些配置,可以在`application.properties`或`application.yml`文件中进行配置。例如,可以配置服务器端口、静态资源路径等。
```yaml
server:
port: 8080
```
5. 运行应用程序:在命令行中执行`mvn spring-boot:run`命令或直接运行主类的`main()`方法,启动应用程序。
现在,你的Spring Boot应用程序已经集成了Spring MVC,并可以通过`http://localhost:8080/hello`访问到`hello()`方法返回的字符串。你可以添加更多的控制器和请求映射方法来构建你的应用程序。