Spring Boot开发三板斧:高效构建企业级应用的核心技法

news2025/4/8 2:27:00

在这里插入图片描述

🧑 博主简介:CSDN博客专家、CSDN平台优质创作者,获得2024年博客之星荣誉证书,高级开发工程师,数学专业,拥有高级工程师证书;擅长C/C++、C#等开发语言,熟悉Java常用开发技术,能熟练应用常用数据库SQL server,Oracle,mysql,postgresql等进行开发应用,熟悉DICOM医学影像及DICOM协议,业余时间自学JavaScript,Vue,qt,python等,具备多种混合语言开发能力。撰写博客分享知识,致力于帮助编程爱好者共同进步。欢迎关注、交流及合作,提供技术支持与解决方案。
技术合作请加本人wx(注明来自csdn):xt20160813

在这里插入图片描述

Spring Boot开发三板斧:高效构建企业级应用的核心技法


第一板斧:RESTful API极速开发

1.1 注解驱动开发

@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor // Lombok自动生成构造器
public class ProductController {

    private final ProductService productService;

    @GetMapping("/{id}")
    public ResponseEntity<ProductDTO> getProduct(@PathVariable Long id) {
        return ResponseEntity.ok(productService.getById(id));
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void createProduct(@Valid @RequestBody ProductCreateRequest request) {
        productService.create(request);
    }

    @ExceptionHandler(ProductNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ProductNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
               .body(new ErrorResponse(ex.getMessage()));
    }
}

核心技巧

  • 使用@RestController组合注解替代@Controller+@ResponseBody
  • 利用Lombok的@RequiredArgsConstructor实现不可变依赖注入
  • 统一异常处理采用@ExceptionHandler+@ControllerAdvice

1.2 接口文档自动化

<!-- Swagger集成依赖 -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.1.0</version>
</dependency>
@OpenAPIDefinition(
    info = @Info(title = "电商平台API", version = "1.0"),
    servers = @Server(url = "/", description = "默认服务器")
)
@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .components(new Components())
            .info(new Info().title("电商平台API"));
    }
}

第二板斧:数据持久化最佳实践

2.1 JPA高效使用

@Entity
@Table(name = "orders")
@Getter @Setter @NoArgsConstructor
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(precision = 10, scale = 2)
    private BigDecimal totalAmount;

    @Enumerated(EnumType.STRING)
    private OrderStatus status;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
    private List<OrderItem> items = new ArrayList<>();

    public void addItem(OrderItem item) {
        items.add(item);
        item.setOrder(this);
    }
}

public interface OrderRepository extends JpaRepository<Order, Long> {
    
    @Query("SELECT o FROM Order o WHERE o.status = :status AND o.createTime > :start")
    List<Order> findRecentByStatus(@Param("status") OrderStatus status,
                                  @Param("start") LocalDateTime startTime);
    
    @Modifying
    @Query("UPDATE Order o SET o.status = :newStatus WHERE o.id = :id")
    int updateStatus(@Param("id") Long orderId, 
                    @Param("newStatus") OrderStatus newStatus);
}

性能优化点

  • 使用@Transactional控制事务边界
  • 批量操作采用@Modifying+@Query
  • N+1查询问题通过@EntityGraph解决

2.2 多数据源配置

spring:
  datasource:
    primary:
      jdbc-url: jdbc:mysql://primary-db:3306/main
      username: admin
      password: ${PRIMARY_DB_PASSWORD}
    secondary:
      jdbc-url: jdbc:mysql://report-db:3306/report
      username: reporter
      password: ${REPORT_DB_PASSWORD}
@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.primary",
    entityManagerFactoryRef = "primaryEntityManager",
    transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDataSourceConfig {
    // 主数据源配置
}

@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.secondary",
    entityManagerFactoryRef = "secondaryEntityManager",
    transactionManagerRef = "secondaryTransactionManager"
)
public class SecondaryDataSourceConfig {
    // 次数据源配置
}

第三板斧:生产级运维保障

3.1 健康监控配置

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      show-details: always
      group:
        db:
          include: db
        custom:
          include: diskSpace
  metrics:
    export:
      prometheus:
        enabled: true

3.2 自定义健康检查

@Component
public class PaymentGatewayHealthIndicator implements HealthIndicator {

    private final PaymentService paymentService;

    @Override
    public Health health() {
        boolean isHealthy = paymentService.checkHealth();
        if (isHealthy) {
            return Health.up()
                   .withDetail("version", "1.2.3")
                   .build();
        }
        return Health.down()
               .withDetail("error", "支付网关无响应")
               .build();
    }
}

3.3 性能指标监控

@Bean
public MeterRegistryCustomizer<PrometheusMeterRegistry> metricsCommonTags() {
    return registry -> registry.config().commonTags(
        "application", "order-service",
        "environment", env.getProperty("spring.profiles.active")
    );
}

三板斧进阶技巧

1. 热部署神器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

效果

  • 修改Java类后自动重启(Classloader级别)
  • 静态资源修改无需重启
  • 默认禁用模板缓存

2. 配置终极方案

@Configuration
@ConfigurationProperties(prefix = "app.notification")
@Data // Lombok自动生成getter/setter
public class NotificationConfig {
    private boolean enabled = true;
    private int retryCount = 3;
    private List<String> channels = List.of("SMS");
    private Map<String, String> templates = new HashMap<>();
}

3. 安全防护标配

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(auth -> auth
                .antMatchers("/api/public/**").permitAll()
                .antMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/dashboard")
            )
            .rememberMe(remember -> remember
                .key("uniqueAndSecret")
                .tokenValiditySeconds(86400)
            )
            .logout(logout -> logout
                .logoutSuccessUrl("/login?logout")
            );
        return http.build();
    }
}

常见问题解决方案

问题1:依赖冲突

# 查看依赖树
mvn dependency:tree -Dincludes=com.fasterxml.jackson.core

# 解决方案:排除冲突依赖
<dependency>
    <groupId>problematic-group</groupId>
    <artifactId>problematic-artifact</artifactId>
    <exclusions>
        <exclusion>
            <groupId>conflict-group</groupId>
            <artifactId>conflict-artifact</artifactId>
        </exclusion>
    </exclusions>
</dependency>

问题2:配置不生效

# 启用配置调试
--debug
# 或在application.yml中设置
debug: true

问题3:性能调优

# 调整Tomcat参数
server:
  tomcat:
    max-threads: 200
    min-spare-threads: 10
    accept-count: 100
    connection-timeout: 5000

# 配置HikariCP连接池
spring:
  datasource:
    hikari:
      maximum-pool-size: 20
      connection-timeout: 30000
      idle-timeout: 600000
      max-lifetime: 1800000

三板斧实战口诀

  1. API开发三步走
    @RestController定框架 → @Service写逻辑 → @Repository管数据

  2. 配置管理三原则
    环境分离(dev/test/prod) → 安全隔离(Vault/加密) → 版本控制(Git管理)

  3. 运维保障三件套
    健康检查(/actuator/health) → 指标监控(Prometheus) → 日志追踪(ELK)

掌握这三项核心技能,即可快速构建符合生产要求的Spring Boot应用。建议从官方Starters列表(spring.io/projects/spring-boot)中选择必要依赖,保持依赖最小化原则,逐步扩展功能模块。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2330167.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

手搓多模态-03 顶层和嵌入层的搭建

声明&#xff1a;本代码非原创&#xff0c;是博主跟着国外大佬的视频教程编写的&#xff0c;本博客主要为记录学习成果所用。 我们首先开始编写视觉模型这一部分&#xff0c;这一部分的主要功能是接收一个batch的图像&#xff0c;并将其转化为上下文相关的嵌入向量&#xff0c;…

【经验分享】将qt的ui文件转换为py文件

&#x1f31f; 嗨&#xff0c;我是命运之光&#xff01; &#x1f30d; 2024&#xff0c;每日百字&#xff0c;记录时光&#xff0c;感谢有你一路同行。 &#x1f680; 携手启航&#xff0c;探索未知&#xff0c;激发潜能&#xff0c;每一步都意义非凡。 首先简单的设计一个U…

探秘JVM内部

在我们编写Java代码&#xff0c;点击运行后&#xff0c;会发生什么事呢&#xff1f; 首先&#xff0c;Java源代码会经过Java编译器将其编译成字节码&#xff0c;放在.class文件中 然后这些字节码文件就会被加载到jvm中&#xff0c;然后jvm会读取这些文件&#xff0c;调用相关…

在HarmonyOS NEXT 开发中,如何指定一个号码,拉起系统拨号页面

大家好&#xff0c;我是 V 哥。 《鸿蒙 HarmonyOS 开发之路 卷1 ArkTS篇》已经出版上市了哈&#xff0c;有需要的朋友可以关注一下&#xff0c;卷2应用开发篇也马上要出版了&#xff0c;V 哥正在紧锣密鼓的写鸿蒙开发实战卷3的教材&#xff0c;卷3主要以项目实战为主&#xff0…

利用空间-运动-回波稀疏性进行5D图像重建,以实现自由呼吸状态下肝脏定量磁共振成像(MRI)的加速采集|文献速递--深度学习医疗AI最新文献

Title 题目 5D image reconstruction exploiting space-motion-echo sparsity foraccelerated free-breathing quantitative liver MRI 利用空间-运动-回波稀疏性进行5D图像重建&#xff0c;以实现自由呼吸状态下肝脏定量磁共振成像&#xff08;MRI&#xff09;的加速采集 …

ZKmall开源商城B2B2C电商用户隐私信息保护策略:数据脱敏全链路实践

随着业务的不断拓展和用户规模的持续扩大&#xff0c;用户隐私信息的保护也面临着前所未有的挑战。下面将深入探讨ZKmall开源商城在数据脱敏方面的实践&#xff0c;以及针对B2B2C电商用户隐私信息的具体保护策略。 数据脱敏&#xff0c;又称数据去标识化或数据匿名化&#xff0…

Pgvector的安装

Pgvector的安装 向量化数据的存储&#xff0c;可以为 PostgreSQL 安装 vector 扩展来存储向量化数据 注意&#xff1a;在安装vector扩展之前&#xff0c;请先安装Postgres数据库 vector 扩展的步骤 1、下载vs_BuildTools 下载地址&#xff1a; https://visualstudio.microso…

Django接入 免费的 AI 大模型——讯飞星火(2025年4月最新!!!)

上文有介绍deepseek接入&#xff0c;但是需要 付费&#xff0c;虽然 sliconflow 可以白嫖 token&#xff0c;但是毕竟是有限的&#xff0c;本文将介绍一款完全免费的 API——讯飞星火 目录 接入讯飞星火&#xff08;免费&#xff09; 测试对话 接入Django 扩展建议 接入讯飞星火…

路由器学习

路由器原理 可以理解成把不同的网络打通&#xff0c;实现通信的设备。比如家里的路由器&#xff0c;他就是把家里的内网和互联网&#xff08;外网&#xff09;打通。 分类 1.&#xff08;按应用场景分类&#xff09; 路由器分为家用的&#xff0c;企业级的&#xff0c;运营…

UE5学习记录part14

第17节 enemy behavior 173 making enemies move: AI Pawn Navigation 按P查看体积 So its very important that our nav mesh bounds volume encompasses all of the area that wed like our 因此&#xff0c;我们的导航网格边界体积必须包含我们希望 AI to navigate in and …

Docker的备份与恢复

一、两种基本方式 docker export / import 在服务器上导出容器docker export container_name > container_backup.tar这里使用 > 重定向时默认保存路径为当前运行命令的路径&#xff0c;可以自行指定绝对路径来保存&#xff0c;后续加载时也使用对应的路径即可。 恢复为…

DAPP实战篇:规划下我们的开发线路

前言 在DApp实战篇&#xff1a;先用前端起个项目一文中我们起了一个前端项目&#xff0c;在后续开发中笔者将带领大家一步步完成这个DAPP&#xff0c;为了方便后续讲解&#xff0c;本篇将完整说明后续我们要进行的开发和思路。 主打前端 实际上一个完整的DAPP是由前端和智能…

【Elasticsearch】开启大数据分析的探索与预处理之旅

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家&#xff0c;历代文学网&#xff08;PC端可以访问&#xff1a;https://literature.sinhy.com/#/literature?__c1000&#xff0c;移动端可微信小程序搜索“历代文学”&#xff09;总架构师&#xff0c;15年工作经验&#xff0c;…

状态机思想编程练习

状态机实现LED流水灯 本次实验&#xff0c;我们将利用状态机的思想来进行Verilog编程实现一个LED流水灯&#xff0c;并通过Modelsim来进行模拟仿真&#xff0c;再到DE2-115开发板上进行验证。 ​ 首先进行主要代码的编写。 module led (input sys_clk,input sys_…

前端新增数据,但数据库里没有新增的数据

先看情况&#xff1a; 1.前端&#xff0c;可以进行删查改&#xff0c;但是新增数据之后&#xff0c;显示保存成功&#xff0c;也增加了空白的一行&#xff0c;但是数据没有显示出来。 2.后端接收到了数据&#xff0c;但返回结果的列表里面是空的&#xff1b;同时数据库里面没…

httpx模块的使用

在使用requests模块发起请求时&#xff0c;报以下错误&#xff0c;表示服务器有可能使用的是http2.0协议版本&#xff0c;导致requests无法爬取。 此时就可以使用httpx模块爬取。 先下载httpx模块&#xff1a; pip install httpx[http2]然后用httpx发起请求&#xff1a; impo…

论文阅读10——解开碳排放与碳足迹之间的关系:文献回顾和可持续交通框架

原文地址: Unraveling the relation between carbon emission and carbon footprint: A literature review and framework for sustainable transportation | npj Sustainable Mobility and TransportTransportation decarbonization has drawn enormous attention globally,…

新一代AI架构实践:数字大脑AI+智能调度MCP+领域执行APP的黄金金字塔体系

新一代AI架构实践&#xff1a;数字大脑智能调度领域执行的黄金金字塔体系 一、架构本质的三层穿透性认知 1.1 核心范式转变&#xff08;CPS理论升级&#xff09; 传统算法架构&#xff1a;数据驱动 → 特征工程 → 模型训练 → 业务应用 新一代AI架构&#xff1a;物理规律建…

Winform MQTT客户端连接方式

项目中使用到Winform的数据转发服务&#xff0c;所以记录下使用到的方法。 一.创建单例模板 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApp.Scripts {public class SingleTon&…

Linux Bash 脚本实战:自动监控域名证书过期并发送邮件告警

在日常运维工作中,SSL 证书的管理是一个非常重要的环节,尤其对于线上业务来说,证书到期会直接导致服务不可用。为了避免证书到期带来的风险,我们可以编写一个 Bash 脚本来自动检测域名的 SSL 证书过期时间,并在证书即将到期时发送告警邮件。 目录 脚本功能概述 代码实现…