Skip to content

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启动类注解
@RestControllerREST 控制器
@RequestMapping请求映射
@GetMapping/PostMappingGET/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-webWeb 开发
spring-boot-starter-data-jpaJPA 数据访问
spring-boot-starter-data-redisRedis
spring-boot-starter-validation参数校验
spring-boot-starter-test测试

总结

  1. 快速启动:SpringApplication.run()
  2. 常用注解:@RestController、@Service、@Repository
  3. Web 开发:RESTful API
  4. 配置管理:application.yml、多环境

基于 VitePress 构建