Spring Boot3入门例子

Spring Boot 3 是一个基于 Spring 框架的快速开发工具,它通过自动配置和约定优于配置的原则,简化了 Spring 应用的创建和部署。在 Spring Boot 3 中,许多新特性和改进被引入,以提高开发效率和应用性能。

Spring Boot 3 是一个基于 Spring 框架的快速开发工具,它通过自动配置和约定优于配置的原则,简化了 Spring 应用的创建和部署。在 Spring Boot 3 中,许多新特性和改进被引入,以提高开发效率和应用性能。以下是对 Spring Boot 3 的一些核心概念和常用注解的详细说明,以及相应的代码示例。

1. Spring Boot 3 简介

Spring Boot 3 引入了对 Java 17+ 的支持,并且对许多内部组件进行了更新和优化。它提供了更好的性能,更少的依赖和更简洁的配置。Spring Boot 3 还引入了一些新的特性,比如对 Jakarta EE 9 的支持,以及对响应式编程的改进。

2. 项目结构

一个典型的 Spring Boot 3 应用通常包含以下结构:

my-spring-boot-app
│
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── myapp
│   │   │               ├── MyApplication.java
│   │   │               ├── controller
│   │   │               │   └── MyController.java
│   │   │               ├── service
│   │   │               │   └── MyService.java
│   │   │               ├── repository
│   │   │               │   └── MyRepository.java
│   │   │               └── component
│   │   │                   └── MyComponent.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── static
│   └── test
│       └── java
│           └── com
│               └── example
│                   └── myapp
│                       └── MyApplicationTests.java
├── pom.xml
└── README.md

3. 主类

在 Spring Boot 3 应用中,主类通常使用 @SpringBootApplication 注解,这个注解是 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 的组合。

package com.example.myapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

4. 控制器

控制器是处理 HTTP 请求和返回 HTTP 响应的组件。在 Spring Boot 3 中,可以使用 @RestController 和 @RequestMapping 注解来创建 RESTful API。

package com.example.myapp.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

5. 服务

服务层通常包含业务逻辑。在 Spring Boot 3 中,可以使用 @Service 注解来标记服务类。

package com.example.myapp.service;

import org.springframework.stereotype.Service;

@Service
public class MyService {

    public String processData(String data) {
        // 业务逻辑处理
        return "Processed: " + data;
    }
}

6. 组件

组件是应用程序中的通用类,可以使用 @Component 注解来标记。

package com.example.myapp.component;

import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    public void performAction() {
        // 执行某些操作
    }
}

7. 数据访问对象(Repository)

数据访问对象(Repository)是用于访问数据库的组件。在 Spring Boot 3 中,可以使用 @Repository 注解来标记。

package com.example.myapp.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MyRepository extends CrudRepository<MyEntity, Long> {
    List<MyEntity> findByAttribute(String attribute);
}

8. 配置类

配置类用于定义 Bean 和其他配置。在 Spring Boot 3 中,可以使用 @Configuration 注解来标记配置类。

package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}

9. 属性文件

Spring Boot 3 允许通过 application.properties 或 application.yml 文件来配置应用程序。

# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=dbuser
spring.datasource.password=dbpass

10. 自动配置

Spring Boot 3 的自动配置机制可以根据添加的依赖自动配置应用程序。例如,添加 spring-boot-starter-web 依赖会自动配置 Tomcat 和 Spring MVC。

11. 测试

Spring Boot 3 提供了对测试的支持,可以使用 @SpringBootTest 和 @Test 注解来编写测试。

package com.example.myapp;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyApplicationTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testHello() {
        String result = restTemplate.getForObject("/hello", String.class);
        assertThat(result).isEqualTo("Hello, World!");
    }
}

12. 响应式编程

Spring Boot 3 支持响应式编程,可以使用 Flux 和 Mono 来处理异步数据流。

package com.example.myapp.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;

@RestController
public class ReactiveController {

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> stream() {
        return Flux
                .interval(Duration.ofSeconds(1))
                .map(sequence -> "Event " + sequence);
    }
}

13. 安全

Spring Boot 3 提供了对 Spring Security 的支持,可以轻松地添加安全和认证。

package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withUsername("user")
                .password("{noop}password")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests
                                .anyRequest().authenticated()
                )
                .httpBasic();
        return http.build();
    }
}

14. 部署

Spring Boot 3 应用可以打包为 JAR 或 WAR 文件,并可以通过多种方式部署,如在 Tomcat、Jetty 或 Undertow 上运行,或者作为独立应用程序。

15. Jakarta EE 9 命名空间变更

Spring Boot 3 将底层依赖从 Java EE 8 升级到了 Jakarta EE 9,最核心的变化是包名前缀从 javax.* 改为 jakarta.*:

旧包名新包名典型场景
javax.servletjakarta.servletSpring MVC Web 应用
javax.persistencejakarta.persistenceJPA 实体映射(如 @Entity, @Id)
javax.validationjakarta.validationBean Validation 校验规则
javax.annotationjakarta.annotation@PostConstruct, @PreDestroy 等通用注解
javax.transactionjakarta.transaction声明式事务管理(@Transactional)

迁移时,IDE 的全局替换功能配合编译报错可快速定位问题。同时注意依赖版本:spring-boot-starter-parent 3.x 已自动引入 jakarta 命名空间的 starter,无需手动指定版本。

16. JPA 与数据访问配置

Spring Boot 3 默认使用 Hibernate 6 作为 JPA 实现,DML 方言更加智能:

# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

Hibernate 6 关键变更:

  • 不再需要手动指定 Dialect,Hibernate 会根据 JDBC URL 自动推断(如 MySQLDialect、PostgreSQLDialect)
  • 原生 SQL 分页不再需要数据库特定语法,Hibernate 自动转换 LIMIT/OFFSET
  • SERIALIZABLE 隔离级别默认禁用乐观锁
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false, length = 50)
    private String username;
    
    @Column(nullable = false, unique = true)
    private String email;
    
    @CreationTimestamp
    private LocalDateTime createdAt;
    
    @UpdateTimestamp
    private LocalDateTime updatedAt;
    
    // getters & setters
}

17. Micrometer 指标监控

Spring Boot 3 将 Metrics 统一迁移到 Micrometer,默认暴露了 http.server.requests 等核心指标:

@Service
public class OrderService {
    
    private final Counter orderCounter;
    private final Timer orderTimer;
    
    public OrderService(MeterRegistry registry) {
        this.orderCounter = Counter.builder("orders.created")
            .description("订单创建计数")
            .register(registry);
        this.orderTimer = Timer.builder("orders.processing.time")
            .description("订单处理耗时")
            .register(registry);
    }
    
    public void createOrder(OrderRequest request) {
        orderTimer.record(() -> {
            // 执行业务逻辑
            orderCounter.increment();
        });
    }
}
# 暴露指标端点
management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.endpoint.health.show-details=always
management.metrics.tags.application=${spring.application.name}

18. Dockerfile 与生产部署

使用分层 JAR 优化 Docker 镜像构建速度和大小:

# Dockerfile
FROM eclipse-temurin:17-jre-alpine as builder
WORKDIR /application
COPY target/*.jar application.jar
RUN java -Djarmode=layertools -jar application.jar extract

FROM eclipse-temurin:17-jre-alpine
WORKDIR /application
# 依赖层(改动最少)
COPY --from=builder application/dependencies/ ./
# 快照依赖层
COPY --from=builder application/spring-boot-loader/ ./
# 应用逻辑层(改动最频繁)
COPY --from=builder application/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

分层构建的缓存优势:

  • dependencies(第三方 jar)几乎不变化,Docker 层可长期缓存
  • application(业务代码)频繁改动,但该层最小(通常 < 5MB)
  • 相比传统 COPY target/*.jar,构建时间减少 60-80%

19. 开发 Tips 速查

场景方案示例
多环境配置application-{profile}.ymlspring.profiles.active=dev
配置属性注入@ConfigurationPropertiesapp.mail.host=localhost
优雅停机server.shutdown=graceful等待正在处理请求完成后关闭
虚拟线程spring.threads.virtual.enabled=trueSpring Boot 3.2+,JDK 21 支持
Native Imagespring-boot-maven-plugin:process-aotGraalVM 原生编译
Bean 延迟初始化spring.main.lazy-initialization=true加快开发启动速度

20. 总结

Spring Boot 3 提供了一套完整的工具和框架,使得开发、配置和部署 Spring 应用变得非常简单。通过使用注解和自动配置,开发者可以快速构建功能丰富的应用程序,而无需进行繁琐的配置。从 Jakarta EE 9 的包名迁移到 Hibernate 6 的自动方言推断,从 Micrometer 的统一指标到分层 Docker 构建,Spring Boot 3 在保持简洁性的同时提供了更多生产环境的实用特性。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「java」更多文章

  1. 《Spring Boot 入门》18.3 打包与运行
  2. 《Spring Boot 入门》18.2 实现
  3. 《Spring Boot 入门》18.1 需求与设计