Spring Boot
Spring Boot 是 Spring 的快速开发框架,简化配置,开箱即用。
快速开始
目录结构
src/main/java/com/example/
├── Application.java # 启动类
├── controller/
├── service/
├── repository/
├── entity/
└── config/主类
java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}pom.xml
xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>常用注解
| 注解 | 说明 |
|---|---|
@SpringBootApplication | 启动类注解 |
@RestController | REST 控制器 |
@RequestMapping | 请求映射 |
@GetMapping/PostMapping | GET/POST 映射 |
@Service | 服务层组件 |
@Repository | 数据访问组件 |
@Component | 通用组件 |
@Configuration | 配置类 |
Web 开发
java
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@GetMapping
public List<User> getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
return userService.findAll(page, size);
}
@PostMapping
public User createUser(@RequestBody @Valid User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.update(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteById(id);
}
}配置管理
application.yml
yaml
server:
port: 8080
spring:
application:
name: myapp
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update
show-sql: true多环境配置
application-dev.yml # 开发环境
application-test.yml # 测试环境
application-prod.yml # 生产环境yaml
# application.yml
spring:
profiles:
active: dev自定义配置
java
@ConfigurationProperties(prefix = "app")
@Component
public class AppProperties {
private String name;
private int maxSize;
// getter/setter
}
# application.yml
app:
name: MyApp
max-size: 100常用 starter
| Starter | 用途 |
|---|---|
| spring-boot-starter-web | Web 开发 |
| spring-boot-starter-data-jpa | JPA 数据访问 |
| spring-boot-starter-data-redis | Redis |
| spring-boot-starter-validation | 参数校验 |
| spring-boot-starter-test | 测试 |
总结
- 快速启动:SpringApplication.run()
- 常用注解:@RestController、@Service、@Repository
- Web 开发:RESTful API
- 配置管理:application.yml、多环境
