
1. Spring框架概述Java生态的基石2003年当Rod Johnson首次提出Spring框架概念时可能没想到它会成为Java企业级开发的标配。如今在招聘网站上搜索Java岗位90%的职位描述都会出现熟悉Spring框架的要求。这个轻量级的IoC容器之所以能统治Java后端开发近二十年核心在于它解决了企业应用开发的三个本质问题对象管理、模块解耦和开发效率。我在2010年第一次接触Spring 2.5时最震撼的是它的依赖注入DI机制。传统JavaEE开发中对象创建和依赖关系硬编码在代码里而Spring通过简单的XML配置就能实现对象生命周期的自动管理。比如数据库连接池这种需要全局共享的资源传统方式要在每个DAO层手动获取而Spring只需要声明一个Beanbean iddataSource classorg.apache.commons.dbcp.BasicDataSource property namedriverClassName valuecom.mysql.jdbc.Driver/ property nameurl valuejdbc:mysql://localhost:3306/mydb/ /bean随着Spring 3.0引入JavaConfig这种配置变得更加类型安全Configuration public class DataSourceConfig { Bean public DataSource dataSource() { return new BasicDataSource(); } }注意虽然现在推荐使用Spring Boot的自动配置但理解底层Bean装配机制对排查复杂依赖问题至关重要。我在处理多数据源配置时就曾因为不了解Bean的加载顺序导致事务管理器注入失败。2. Spring核心机制深度解析2.1 IoC容器工作原理Spring的核心是它的IoC容器本质上是一个管理Bean生命周期的工厂模式实现。但比普通工厂更强大的是它支持依赖查找DL通过BeanFactory.getBean()显式获取对象依赖注入DI通过构造函数、setter或字段自动装配生命周期回调PostConstruct、InitializingBean等初始化钩子容器启动时会经历几个关键阶段Bean定义加载解析Configuration类或XML文件生成BeanDefinition依赖关系解析处理Autowired等注解构建依赖图循环依赖处理通过三级缓存解决后面会详细说明Bean实例化通过反射创建对象并注入依赖AOP代理创建如果需要生成JDK动态代理或CGLIB代理// 典型的三级缓存结构源码示意 public class DefaultSingletonBeanRegistry { // 一级缓存存放完整Bean private final MapString, Object singletonObjects new ConcurrentHashMap(); // 二级缓存存放早期引用未完成初始化的Bean private final MapString, Object earlySingletonObjects new HashMap(); // 三级缓存存放Bean工厂用于解决循环依赖 private final MapString, ObjectFactory? singletonFactories new HashMap(); }2.2 AOP实现原理Spring AOP的底层是动态代理但具体实现会根据目标类选择不同策略代理类型条件性能限制JDK动态代理实现接口较快只能代理接口方法CGLIB代理无接口稍慢不能代理final方法实际开发中事务管理(Transactional)和缓存(Cacheable)都是基于AOP实现的。我曾遇到一个性能问题在内部方法调用Transactional方法时事务不生效这是因为Service public class OrderService { // 外部调用走代理事务生效 public void createOrder() { validate(); // 内部调用不走代理事务不生效 } Transactional public void validate() {...} }解决方案是注入self引用或使用AspectJ编译时织入Service public class OrderService { Autowired private OrderService self; // 注入自身代理 public void createOrder() { self.validate(); // 通过代理调用 } }3. Spring Boot的自动化魔法3.1 自动配置原理Spring Boot的EnableAutoConfiguration背后是spring.factories机制。以JDBC自动配置为例检测到DataSource.class在classpath查找META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports加载DataSourceAutoConfiguration根据application.properties配置连接池自定义starter时需要创建autoconfigure模块添加Configuration类在META-INF/spring下添加配置# 示例自定义starter的spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration\ com.example.MyAutoConfiguration3.2 监控与ActuatorSpring Boot Actuator提供了生产级监控端点management: endpoints: web: exposure: include: * endpoint: health: show-details: always metrics: enabled: true常用端点/health - 应用健康状态/metrics - JVM指标/threaddump - 线程快照/heapdump - 堆转储(需谨慎开启)警告生产环境务必保护/actuator端点我曾遇到因未设权限导致数据库连接池配置泄露的安全事故。4. Spring Cloud微服务实践4.1 服务注册与发现Spring Cloud支持多种注册中心以Nacos为例SpringBootApplication EnableDiscoveryClient public class ProductService { public static void main(String[] args) { SpringApplication.run(ProductService.class, args); } }配置示例spring: cloud: nacos: discovery: server-addr: 127.0.0.1:8848 config: server-addr: 127.0.0.1:8848 file-extension: yaml4.2 分布式事务解决方案对于跨服务事务常见方案对比方案原理一致性性能复杂度2PC协调者模式强一致差高TCCTry-Confirm-Cancel最终一致中高SAGA事件补偿最终一致好中本地消息表异步确保最终一致好低Seata的AT模式使用示例GlobalTransactional public void purchase() { orderService.create(); storageService.deduct(); accountService.debit(); }5. 性能优化实战经验5.1 缓存策略Spring Cache抽象支持多种实现Cacheable(valueusers, key#userId, unless#resultnull) public User getUser(Long userId) { return userRepository.findById(userId); } CacheEvict(valueusers, key#user.id) public void updateUser(User user) { userRepository.update(user); }缓存穿透解决方案空值缓存cache-null-valuestrueBloom过滤器互斥锁5.2 连接池优化以HikariCP为例的关键参数spring.datasource.hikari.maximum-pool-size20 spring.datasource.hikari.minimum-idle10 spring.datasource.hikari.idle-timeout30000 spring.datasource.hikari.connection-timeout3000 spring.datasource.hikari.max-lifetime1800000监控指标activeConnectionsidleConnectionsthreadsAwaitingConnectionconnectionTimeout6. 常见问题排查指南6.1 Bean创建异常典型错误BeanCurrentlyInCreationException排查步骤检查是否存在构造器循环依赖使用Lazy延迟加载改为setter注入// 错误示例 Service public class A { private final B b; public A(B b) { this.b b; } } Service public class B { private final A a; public B(A a) { this.a a; } } // 解决方案 Service public class A { Lazy private final B b; public A(B b) { this.b b; } }6.2 事务失效场景方法非public自调用问题异常类型不匹配数据库引擎不支持(如MyISAM)验证方法TransactionSynchronizationManager.isActualTransactionActive()7. 现代Spring技术演进7.1 Spring NativeGraalVM原生镜像支持./mvnw spring-boot:build-image限制反射需要预先配置动态代理有限制类加载行为不同7.2 Spring AI集成大语言模型示例RestController public class ChatController { private final ChatClient chatClient; public String generate(RequestParam String message) { return chatClient.call(message); } }配置spring: ai: openai: api-key: ${OPENAI_API_KEY}8. 架构设计最佳实践8.1 分层规范推荐结构com.example ├── application # 应用服务层 ├── domain # 领域模型 ├── infrastructure # 基础设施 │ ├── config # 配置类 │ ├── repository # 持久化 │ └── client # 外部服务调用 └── interfaces # 接口层 ├── web # 控制器 └── dto # 数据传输对象8.2 测试策略测试金字塔实现// 单元测试 ExtendWith(MockitoExtension.class) class OrderServiceTest { Mock private PaymentGateway gateway; InjectMocks private OrderService service; } // 集成测试 SpringBootTest class OrderIntegrationTest { Autowired private TestRestTemplate restTemplate; } // 契约测试 SpringBootTest(webEnvironment WebEnvironment.DEFINED_PORT) AutoConfigureStubRunner class ContractTest {}9. 从Spring到云原生9.1 Kubernetes集成Deployment配置示例apiVersion: apps/v1 kind: Deployment spec: containers: - name: app image: my-spring-app env: - name: SPRING_PROFILES_ACTIVE value: prod readinessProbe: httpGet: path: /actuator/health port: 80809.2 Service Mesh整合通过Istio实现注入sidecaristioctl kube-inject -f deployment.yaml配置流量规则apiVersion: networking.istio.io/v1alpha3 kind: VirtualService spec: hosts: - orderservice http: - route: - destination: host: orderservice subset: v1 timeout: 2s10. 开发者生产力工具10.1 IDE插件IntelliJ IDEA必备插件Spring AssistantSpring Boot ToolsLombok10.2 CLI工具Spring CLI示例# 创建项目 spring init --dependenciesweb,lombok myproject # 运行测试 spring test # 查看Bean依赖图 spring graph11. 安全防护方案11.1 认证授权Spring Security配置Configuration EnableWebSecurity public class SecurityConfig { Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth - auth .requestMatchers(/public/**).permitAll() .anyRequest().authenticated() ) .formLogin(withDefaults()); return http.build(); } }11.2 漏洞防护常见防护措施CSRF保护默认开启响应头安全配置输入验证SQL注入防护使用JPA/Hibernate参数化查询12. 未来技术展望Spring Framework 6.0方向JDK 17基线支持更好的GraalVM兼容性响应式编程增强更深的云原生集成响应式编程示例RestController public class ReactiveController { GetMapping(/flux) public FluxString getFlux() { return Flux.just(A, B, C) .delayElements(Duration.ofSeconds(1)); } }在微服务架构设计中Spring Cloud Gateway作为API网关的配置示例spring: cloud: gateway: routes: - id: product-service uri: lb://product-service predicates: - Path/api/products/** filters: - name: CircuitBreaker args: name: productCircuitBreaker fallbackUri: forward:/fallback/product对于需要处理高并发的场景WebFlux提供了更高效的解决方案RestController RequestMapping(/reactive) public class ReactiveOrderController { private final ReactiveOrderService orderService; GetMapping(/orders/{id}) public MonoOrder getOrder(PathVariable String id) { return orderService.findById(id) .timeout(Duration.ofSeconds(1)) .onErrorResume(e - Mono.just(new Order(fallback))); } PostMapping(/orders) public MonoVoid createOrder(RequestBody MonoOrder orderMono) { return orderMono .flatMap(orderService::save) .then(); } }在持续集成环境中Spring应用的Docker化构建可以这样优化# 多阶段构建减少镜像体积 FROM eclipse-temurin:17-jdk-jammy as builder WORKDIR /app COPY . . RUN ./mvnw clean package -DskipTests FROM eclipse-temurin:17-jre-jammy WORKDIR /app COPY --frombuilder /app/target/*.jar app.jar ENTRYPOINT [java,-jar,app.jar]对于需要国际化的应用Spring的MessageSource可以这样配置Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource new ReloadableResourceBundleMessageSource(); messageSource.setBasenames(classpath:messages); messageSource.setDefaultEncoding(UTF-8); messageSource.setCacheSeconds(3600); return messageSource; } // 使用示例 RestController public class GreetingController { Autowired private MessageSource messageSource; GetMapping(/greet) public String greet(Locale locale) { return messageSource.getMessage(welcome.message, null, locale); } }在处理文件上传时Spring提供了灵活的配置选项Bean public MultipartResolver multipartResolver() { CommonsMultipartResolver resolver new CommonsMultipartResolver(); resolver.setMaxUploadSize(10485760); // 10MB resolver.setDefaultEncoding(UTF-8); return resolver; } PostMapping(/upload) public String handleUpload(RequestParam(file) MultipartFile file) { if (!file.isEmpty()) { String fileName StringUtils.cleanPath(file.getOriginalFilename()); Path path Paths.get(/uploads/ fileName); Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); return Upload success; } return Upload failed; }对于需要定时任务的应用Spring的Scheduler提供了多种配置方式Configuration EnableScheduling public class SchedulingConfig implements SchedulingConfigurer { Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } Bean(destroyMethodshutdown) public Executor taskExecutor() { return Executors.newScheduledThreadPool(10); } } Component public class ReportGenerator { Scheduled(cron 0 0 2 * * ?) // 每天凌晨2点 public void generateDailyReport() { // 报表生成逻辑 } Scheduled(fixedRate 3600000) // 每小时执行 public void refreshCache() { // 缓存刷新逻辑 } }在需要处理异步任务时Spring的Async注解提供了简单实现Configuration EnableAsync public class AsyncConfig implements AsyncConfigurer { Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setThreadNamePrefix(Async-); executor.initialize(); return executor; } } Service public class NotificationService { Async public CompletableFutureString sendEmail(String to, String content) { // 模拟耗时操作 Thread.sleep(1000); return CompletableFuture.completedFuture(Email sent to to); } }对于需要处理复杂业务逻辑的场景Spring的Validator接口提供了强大的校验能力public class OrderValidator implements Validator { Override public boolean supports(Class? clazz) { return Order.class.isAssignableFrom(clazz); } Override public void validate(Object target, Errors errors) { Order order (Order) target; if (order.getItems() null || order.getItems().isEmpty()) { errors.rejectValue(items, empty, Order must contain at least one item); } if (order.getTotalAmount().compareTo(BigDecimal.ZERO) 0) { errors.rejectValue(totalAmount, invalid, Total amount must be positive); } } } RestController RequestMapping(/orders) public class OrderController { Autowired private OrderValidator validator; PostMapping public ResponseEntity? createOrder(RequestBody Order order, BindingResult result) { validator.validate(order, result); if (result.hasErrors()) { return ResponseEntity.badRequest().body(result.getAllErrors()); } // 处理订单创建 return ResponseEntity.ok().build(); } }在处理分布式锁场景时Spring Integration提供了跨平台的解决方案Configuration EnableIntegration public class LockConfig { Bean public RedisLockRegistry redisLockRegistry(RedisConnectionFactory factory) { return new RedisLockRegistry(factory, lockRegistry); } } Service public class InventoryService { Autowired private LockRegistry lockRegistry; public void updateStock(String productId, int quantity) { Lock lock lockRegistry.obtain(productId); try { if (lock.tryLock(3, TimeUnit.SECONDS)) { try { // 执行库存更新 } finally { lock.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }对于需要处理多种数据格式的REST APISpring的内容协商机制非常有用Configuration public class WebConfig implements WebMvcConfigurer { Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer .favorParameter(true) .parameterName(format) .ignoreAcceptHeader(false) .defaultContentType(MediaType.APPLICATION_JSON) .mediaType(json, MediaType.APPLICATION_JSON) .mediaType(xml, MediaType.APPLICATION_XML); } } RestController RequestMapping(/products) public class ProductController { GetMapping(produces {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public ListProduct listProducts() { return productService.findAll(); } }在处理大文件下载时Spring的StreamingResponseBody提供了高效的内存解决方案GetMapping(/download/{fileId}) public ResponseEntityStreamingResponseBody downloadFile(PathVariable String fileId) { File file fileService.getFile(fileId); StreamingResponseBody body outputStream - { try (InputStream inputStream new FileInputStream(file)) { byte[] buffer new byte[8192]; int bytesRead; while ((bytesRead inputStream.read(buffer)) ! -1) { outputStream.write(buffer, 0, bytesRead); } } }; return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, attachment; filename\ file.getName() \) .contentLength(file.length()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(body); }对于需要自定义错误处理的场景Spring的ControllerAdvice提供了全局解决方案ControllerAdvice public class GlobalExceptionHandler { ExceptionHandler(ResourceNotFoundException.class) public ResponseEntityErrorResponse handleNotFound(ResourceNotFoundException ex) { ErrorResponse response new ErrorResponse( NOT_FOUND, ex.getMessage(), Instant.now() ); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); } ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntityErrorResponse handleValidation(MethodArgumentNotValidException ex) { ListString errors ex.getBindingResult() .getFieldErrors() .stream() .map(fe - fe.getField() : fe.getDefaultMessage()) .collect(Collectors.toList()); ErrorResponse response new ErrorResponse( VALIDATION_FAILED, Invalid request parameters, Instant.now(), errors ); return ResponseEntity.badRequest().body(response); } }在处理前后端分离项目中的CORS问题时Spring提供了灵活的配置选项Configuration public class CorsConfig implements WebMvcConfigurer { Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping(/api/**) .allowedOrigins(https://frontend.com) .allowedMethods(GET, POST, PUT, DELETE) .allowedHeaders(*) .exposedHeaders(X-Custom-Header) .allowCredentials(true) .maxAge(3600); } }对于需要处理WebSocket通信的场景Spring提供了完整的支持Configuration EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker(/topic); config.setApplicationDestinationPrefixes(/app); } Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(/ws) .setAllowedOrigins(*) .withSockJS(); } } Controller public class NotificationController { MessageMapping(/notify) SendTo(/topic/notifications) public Notification sendNotification(NotificationMessage message) { return new Notification(New message from message.getSender()); } }在处理服务器推送事件(SSE)时Spring的SseEmitter提供了简洁的APIRestController RequestMapping(/sse) public class SseController { private final MapString, SseEmitter emitters new ConcurrentHashMap(); GetMapping(/subscribe/{id}) public SseEmitter subscribe(PathVariable String id) { SseEmitter emitter new SseEmitter(3600000L); // 1小时超时 emitters.put(id, emitter); emitter.onCompletion(() - emitters.remove(id)); emitter.onTimeout(() - emitters.remove(id)); return emitter; } PostMapping(/send/{id}) public void sendEvent(PathVariable String id, RequestBody String message) { SseEmitter emitter emitters.get(id); if (emitter ! null) { try { emitter.send(SseEmitter.event() .name(message) .data(message)); } catch (IOException e) { emitters.remove(id); } } } }在处理GraphQL API时Spring GraphQL提供了完整的支持Controller public class BookController { QueryMapping public Book bookById(Argument String id) { return bookRepository.findById(id); } MutationMapping public Book addBook(Argument String name, Argument int pageCount) { return bookRepository.save(new Book(name, pageCount)); } SchemaMapping(typeName Book, field author) public Author getAuthor(Book book) { return authorRepository.findByBookId(book.id()); } }对于需要处理RSocket通信的场景Spring提供了响应式支持Controller MessageMapping(users.) public class UserRSocketController { MessageMapping(get) public MonoUser getUser(Payload String userId) { return userRepository.findById(userId); } MessageMapping(update) public MonoVoid updateUser(Payload User user) { return userRepository.save(user).then(); } MessageMapping(stream) public FluxUser streamUsers() { return userRepository.findAll(); } }在处理函数式Web端点时Spring WebFlux提供了RouterFunction方式Configuration public class RouterConfig { Bean public RouterFunctionServerResponse routes(UserHandler userHandler) { return RouterFunctions.route() .GET(/users, userHandler::listUsers) .GET(/users/{id}, userHandler::getUser) .POST(/users, userHandler::createUser) .build(); } } Component public class UserHandler { private final UserRepository repository; public MonoServerResponse listUsers(ServerRequest request) { return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(repository.findAll(), User.class); } public MonoServerResponse getUser(ServerRequest request) { return repository.findById(request.pathVariable(id)) .flatMap(user - ServerResponse.ok().bodyValue(user)) .switchIfEmpty(ServerResponse.notFound().build()); } }在处理多数据源场景时Spring的AbstractRoutingDataSource提供了动态切换能力public class TenantDataSource extends AbstractRoutingDataSource { Override protected Object determineCurrentLookupKey() { return TenantContext.getCurrentTenant(); } } Configuration public class DataSourceConfig { Bean ConfigurationProperties(spring.datasource.master) public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } Bean ConfigurationProperties(spring.datasource.tenant) public DataSource tenantDataSource() { return DataSourceBuilder.create().build(); } Bean public DataSource routingDataSource( Qualifier(masterDataSource) DataSource master, Qualifier(tenantDataSource) DataSource tenant) { TenantDataSource routingDataSource new TenantDataSource(); MapObject, Object targetDataSources new HashMap(); targetDataSources.put(master, master); targetDataSources.put(tenant, tenant); routingDataSource.setTargetDataSources(targetDataSources); routingDataSource.setDefaultTargetDataSource(master); return routingDataSource; } }在处理数据库迁移时Spring的Flyway/Liquibase集成非常有用spring: flyway: enabled: true locations: classpath:db/migration baseline-on-migrate: true validate-on-migrate: false-- src/main/resources/db/migration/V1__Initial_schema.sql CREATE TABLE users ( id BIGINT PRIMARY KEY, username VARCHAR(50) NOT NULL );对于需要处理审计日志的场景Spring Data提供了方便的审计功能Configuration EnableJpaAuditing public class AuditConfig { Bean public AuditorAwareString auditorAware() { return () - Optional.ofNullable(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .filter(Authentication::isAuthenticated) .map(Authentication::getName); } } Entity EntityListeners(AuditingEntityListener.class) public class Order { Id private Long id; CreatedBy private String createdBy; CreatedDate private Instant createdDate; LastModifiedBy private String lastModifiedBy; LastModifiedDate private Instant lastModifiedDate; }在处理多租户SaaS应用时Spring的Hibernate过滤器很有帮助Entity FilterDef( name tenantFilter, parameters ParamDef(name tenantId, type String.class) ) Filter( name tenantFilter, condition tenant_id :tenantId ) public class Product { Column(name tenant_id) private String tenantId; } Configuration public class HibernateConfig { Bean public FilterRegistrationBeanOpenSessionInViewFilter hibernateFilter() { FilterRegistrationBeanOpenSessionInViewFilter registration new FilterRegistrationBean(); registration.setFilter(new OpenSessionInViewFilter()); registration.addInitParameter( sessionFactoryBeanName, sessionFactory ); return registration; } } Aspect Component public class TenantFilterAspect { Autowired private EntityManager entityManager; Before(execution(* com.example.repository.*.*(..))) public void enableFilter() { Session session entityManager.unwrap(Session.class); session.enableFilter(tenantFilter) .setParameter(tenantId, TenantContext.getCurrentTenant()); } }在处理分布式缓存时Spring Cache与Redis的集成方案Configuration EnableCaching public class CacheConfig { Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(30)) .disableCachingNullValues() .serializeValuesWith(SerializationPair.fromSerializer( new GenericJackson2JsonRedisSerializer() )); return RedisCacheManager.builder(factory) .cacheDefaults(config) .transactionAware() .build(); } } Service public class ProductService { Cacheable(value products, key #id) public Product getProduct(Long id) { return productRepository.findById(id); } CacheEvict(value products, key #product.id) public void updateProduct(Product product) { productRepository.save(product); } CachePut(value products, key #product.id) public Product refreshProduct(Product product) { return productRepository.save(product); } }在处理分布式会话时Spring Session提供了多种存储方案spring: session: store-type: redis timeout: 1800 redis: namespace: spring:sessionRestController public class SessionController { GetMapping(/session) public String getSessionId(HttpSession session) { return session.getId(); } GetMapping(/attr) public String getAttribute(SessionAttribute String username) { return Hello username; } }在处理API版本控制时Spring提供了多种策略RestController RequestMapping(/api/v1/products) public class ProductControllerV1 { // 旧版API实现 } RestController RequestMapping(/api/v2/products) public class ProductControllerV2 { // 新版API实现 } // 或者使用内容协商 GetMapping(value /products, produces application/vnd.company.api.v1json) public ResponseEntity? getProductsV1() { // 版本1实现 } GetMapping(value /products, produces application/vnd.company.api.v2json) public ResponseEntity? getProductsV2() { // 版本2实现 }在处理文件导出为Excel时Spring与Apache POI的集成方案GetMapping(/export) public void exportProducts(HttpServletResponse response) throws IOException { ListProduct products productService.findAll(); response.setContentType(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet); response.setHeader(Content-Disposition, attachment; filenameproducts.xlsx); try (Workbook workbook new XSSFWorkbook()) { Sheet sheet workbook.createSheet(Products); // 创建表头 Row headerRow sheet.createRow(0); headerRow.createCell(0).setCellValue(ID); headerRow.createCell(1).setCellValue(Name); // 填充数据 int rowNum 1; for (Product product : products) { Row row sheet.createRow(rowNum); row.createCell(0).setCellValue(product.getId()); row.createCell(1).setCellValue(product.getName()); } workbook.write(response.getOutputStream()); } }在处理PDF生成时Spring与iText/Flying Saucer的集成方案GetMapping(/report) public void generatePdf(HttpServletResponse response) throws Exception { ListOrder orders orderService.findAll(); response.setContentType(application/pdf); response.setHeader(Content-Disposition, attachment; filenameorders.pdf); // 使用Thymeleaf模板生成HTML Context context new Context(); context.setVariable(orders, orders); String html templateEngine.process(order-report, context); // 转换为PDF try (OutputStream os response.getOutputStream()) { ITextRenderer renderer new ITextRenderer(); renderer.setDocumentFromString(html); renderer.layout(); renderer.createPDF(os); } }在处理邮件发送时Spring Mail的配置与使用spring: mail: host: smtp.example.com port: 587 username: userexample.com password: password properties: mail: smtp: auth: true starttls.enable: trueService public class EmailService { Autowired private JavaMailSender mailSender; Async public void sendEmail(String to, String subject, String text) { SimpleMailMessage message new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } public void sendHtmlEmail(String to, String subject, String templateName, MapString, Object model) throws MessagingException { MimeMessage message mailSender.createMimeMessage(); MimeMessageHelper helper new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); // 使用Thymeleaf模板 Context context new Context(); context.setVariables(model); String html templateEngine.process(templateName, context); helper.setText(html, true); mailSender.send(message); } }在处理支付集成时Spring与Stripe/PayPal的集成示例Service public class PaymentService { Value(${stripe.se