SpringBoot快速创建WEB项目
SpringBoot 简化了 Spring 项目配置,可快速搭建 WEB 应用。
项目创建方式
Spring Initializr
访问 https://start.spring.io/ ,选择配置后生成项目。
IDEA创建
- New Project → Spring Initializr
- 选择依赖:Spring Web
- 生成项目结构
Maven命令
Bash
mvn archetype:generate \
-DgroupId=com.example \
-DartifactId=demo \
-DarchetypeArtifactId=maven-archetype-quickstart
项目结构
XML
demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/
│ │ │ ├── DemoApplication.java
│ │ │ └── controller/
│ │ │ └── HelloController.java
│ │ └── resources/
│ │ ├── application.yml
│ │ ├── static/
│ │ └── templates/
│ └── test/
│ └── java/
│ └── com/example/
│ └── DemoApplicationTests.java
├── pom.xml
pom.xml配置
Java
<?xml version="1.0" encoding="UTF-8"?>
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0.0</version>
<dependencies>
<!-- Web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
启动类
Java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@SpringBootApplication解析
Java
@SpringBootApplication = @SpringBootConfiguration
+ @EnableAutoConfiguration
+ @ComponentScan
| 注解 | 作用 |
|---|---|
| @SpringBootConfiguration | 配置类,等同于@Configuration |
| @EnableAutoConfiguration | 自动配置 |
| @ComponentScan | 组件扫描,默认扫描当前包及子包 |
Hello World示例
YAML
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, SpringBoot!";
}
@GetMapping("/hello/{name}")
public String helloName(@PathVariable String name) {
return "Hello, " + name + "!";
}
}
application.yml配置
Bash
server:
port: 8080
servlet:
context-path: /
spring:
application:
name: demo
logging:
level:
root: info
com.example: debug
启动项目
Bash
# Maven启动
mvn spring-boot:run
# 打jar包运行
mvn clean package
java -jar target/demo-1.0.0.jar
# IDEA直接运行
运行 DemoApplication.main()
常用starter依赖
| Starter | 功能 |
|---|---|
| spring-boot-starter-web | Web开发 |
| spring-boot-starter-data-jpa | JPA数据库 |
| spring-boot-starter-data-redis | Redis |
| spring-boot-starter-security | 安全框架 |
| spring-boot-starter-actuator | 监控端点 |
| spring-boot-starter-validation | 参数校验 |
访问测试
text
curl http://localhost:8080/hello
# 输出: Hello, SpringBoot!
curl http://localhost:8080/hello/张三
# 输出: Hello, 张三!
要点总结
- 使用Spring Initializr快速创建项目
- spring-boot-starter-web包含Web开发所需依赖
- @SpringBootApplication是核心启动注解
- 默认端口8080,可通过application.yml修改
- mvn spring-boot:run快速启动项目
📝 发现内容有误?点击此处直接编辑