Spring Boot 对 JDBC 的支持 Spring 的 JdbcTemplate 在 DataSource 的基础上提供了执行数据库操作的高级抽象。配合 Spring 的声明式事务,能以很简单的方式管理数据库事务,而无需编写模板式的代码。
Spring Boot 通过自动配置机制简化了 DataSource、TransactionManager 等的配置。
让我们看看如何使用 JdbcTemplate 对 PostgreSQL 数据库执行 CRUD 操作。
首先,访问 https://start.springboot.io/,选择 JDBC API、PostgreSQL Driver 和 Testcontainers starter,创建 Spring Boot 应用程序。
假设,我们正在开发一个管理书签(bookmarks)的简单应用。因此,我们将创建包含 id、title、url 和 created_at 列的 bookmarks 表。
初始化数据源 Spring Boot 提供了一种方便的数据库初始化机制。我们可以在 src/main/resources 下创建 schema.sql 和 data.sql 文件,这些文件将在启动应用程序时自动执行。不过,只有在使用 HSQL、H2 等内存数据库时,才会默认启用自动脚本执行功能,否则就会禁用。
我们可以在 src/main/resources/application.properties 文件中添加以下属性来启用脚本初始化。
spring.sql.init.mode=always 现在,让我们创建 src/main/resources/schema.sql 文件,如下所示:
create table if not exists bookmarks ( id bigserial not null, title varchar not null, url varchar not null, created_at timestamp, primary key (id) ); 要插入一些示例数据,请创建 src/main/resources/data.
在 Spring Boot 应用中使用 Spring Cache 管理缓存时,可以通过调用 @CacheEvict(allEntries=true) 注解的方法来批量删除当前缓存(cacheNames) 下的所有缓存项目。如下:
package cn.springdoc.demo.cache; import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Component; @Component public class FooCahe { // 清除 “foo” 命名空间下的所有缓存项目 @CacheEvict(cacheNames = "foo", allEntries = true) public void clear () { } } 如果你的 Spring Cache 使用的缓存实现是 Redis,那么默认情况下它会使用 KEYS [pattern] 指令来获取、删除所有匹配的缓存项目。
测试方法如下:
package cn.springdoc.demo; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import cn.springdoc.demo.cache.FooCahe; @SpringBootTest(classes = SpringdocCacheApplication.class) class SpringdocCacheApplicationTests { static final Logger logger = LoggerFactory.
1、概览 在本教程中,我们将探索 Spring 框架中不同的错误响应格式。我们还将了解如何使用自定义属性抛出和处理 RFC7807 ProblemDetail,以及如何在 Spring WebFlux 中抛出自定义异常。
2、Spring Boot 3 中的异常响应格式 让我们来了解一下开箱即用的各种错误响应格式。
默认情况下,Spring Framework 提供了实现 ErrorAttributes 接口的 DefaultErrorAttributes 类,用于在出现未处理的错误时生成错误响应。在默认错误的情况下,系统会生成一个 JSON 响应,提供了一些详细的信息:
{ "timestamp": "2023-04-01T00:00:00.000+00:00", "status": 500, "error": "Internal Server Error", "path": "/api/example" } 虽然该错误响应包含一些关键属性,但可能对排除问题没有帮助。幸运的是,我们可以通过在 Spring WebFlux 应用程序中创建 ErrorAttributes 接口的自定义实现来修改默认行为。
从 Spring Framework 6 ProblemDetail 开始,支持 RFC7807 规范的表示。ProblemDetail 包含一些定义错误细节的标准属性,还提供了扩展细节以进行自定义的选项。支持的属性如下所示:
type(string) - 标识问题类型的 URI 参考地址。 title(string) - 问题类型简述。 status(number) - HTTP 状态码。 detail(string) - 应包含异常的详细信息。 instance(string) - 一个 URI 参考地址,用于标识问题的具体原因。例如,它可以指向导致问题的属性。 除了上述标准属性外,ProblemDetail 还包含一个 Map<String, Object>,用于添加自定义参数,以提供有关问题的更详细信息。
1、概览 Spring Boot 项目 是 Spring 框架的扩展,它提供的功能有助于创建基于 Spring 的独立应用程序,并支持云原生开发。
有时,我们并不想使用 Spring Boot,例如在将 Spring Framework 整合到 Jakarta EE 应用程序时,但我们仍然希望受益于生产就绪功能,如指标和健康检查,即所谓的 “可观察性”。(可在 “Spring Boot 3 和 Observability(可观察性)” 一文中找到详细信息)。
可观察性功能由 Spring Boot Actuator 提供,它是 Spring Boot 的一个子项目。在本文中,我们将了解如何将 Actuator 整合到非 Spring Boot 的应用程序中。
2、项目配置 如果不使用 Spring Boot,我们就需要处理应用打包和服务器运行时配置的问题,还需要自己将 配置外部化,当然,本文并不会涉及这些内容。由于我们不能直接使用 Spring Boot 的 Starter 依赖(本例中为 spring-boot-starter-actuator),因此我们需要在 application context 中手动添加必要的 Bean。
我们可以手动配置,也可以使用自动配置。因为 Actuator 的配置相当复杂,而且没有任何详细的文档说明,所以我们应该选择自动配置。这是我们需要 Spring Boot 的原因之一,因此我们不能完全排除 Spring Boot。
2.1、添加项目依赖 要集成 Actuator,我们需要 Spring-boot-actuator-autoconfigure 依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator-autoconfigure</artifactId> <version>3.0.6</version> </dependency> 这也将通过传递依赖 spring-boot-actuator、spring-boot 和 spring-boot-autoconfigure。
1、简介 Spring Boot Gradle Plugin 在 Gradle 中提供 Spring Boot 支持。它允许我们打包可执行的 JAR 或 war 文件,运行 Spring Boot 应用程序,并使用 spring-boot-dependencies 提供的依赖管理。Spring Boot 3 Gradle Plugin 需要 Gradle 7.x (7.5 或更高版本)或 8.x,并可与 Gradle 的配置缓存一起使用。
在这个教程中,我们将学习关于 Spring Boot 3 Gradle Plugin Task 配置的内容。Spring Boot 3 Gradle Plugin 提供了几个 Gradle task 可用。我们将使用一个简单的 Spring Boot 应用来演示如何配置一些 task。出于演示的目的,我们不会添加任何 security 配置或数据到我们的 Spring Boot 应用中。话不多说,现在让我们深入详细定义和配置这些 task。
2、配置 bootJar Gradle Task 在 Spring Boot 3 Gradle Plugin中,Gradle task 比以前的版本有所改进。一些常见的 Gradle task 包括 bootJar、bootWar、bootRun 和 bootBuildImage。让我们深入了解 bootJar,看看如何配置 bootJar task。
1、概览 在教程中,我们将仔细研究 Spring Boot 中出现的错误:Reason: Canonical names should be kebab-case (’-’ separated), lowercase alpha-numeric characters, and must start with a letter。
首先,我们将阐明 Spring Boot 中出现此错误的主要原因。然后,我们将通过一个实际示例深入探讨如何重现和解决这个问题。
2、问题说明 首先,让我们了解一下错误信息的含义。“Canonical names should be kebab-case” 意思是“规范名称应使用短横线命名法(kebab-case)”。
为确保一致性,@ConfigurationProperties 注解的 prefix 参数中使用的命名约定应遵循短横线命名格式。
例如:
@ConfigurationProperties(prefix = "my-example") 3、Maven 依赖 在 pom.xml 中添加必要的依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.0.5</version> </dependency> spring-boot-starter 是重现问题的唯一依赖。
4、重现问题 4.1、应用配置 注册所需的组件:
@Configuration @ConfigurationProperties(prefix = "customProperties") public class MainConfiguration { String name; // get/set 方法省略 } 然后,我们需要在 application.
1、Spring Cache 的简介 Spring Cache 是 Spring 框架提供的一个缓存抽象层,用于简化应用中的缓存操作。它通过在方法执行期间将结果存储在缓存中,以便在相同的输入参数下,下一次调用时可以直接从缓存中获取结果,而不必执行相同的计算或查询操作。Spring Cache 支持多种缓存提供商,如 Ehcache、Redis、Caffeine 等,可以根据需求选择合适的缓存实现。通过使用 Spring Cache,开发人员可以轻松地添加缓存功能,提高应用的性能和响应速度。
Redis 是 Spring Cache 中最常用的缓存实现之一,有以下几个主要原因:
高性能:Redis 是一个基于内存的数据存储系统,具有非常高的读写性能。它将数据存储在内存中,可以快速地读取和写入数据,适合作为缓存存储。 数据结构丰富:Redis 支持多种数据结构,如字符串、哈希、列表、集合和有序集合等,这些数据结构的灵活性可以满足不同场景下的缓存需求。 持久化支持:Redis 提供了持久化机制,可以将数据存储到磁盘上,以防止数据丢失。这对于缓存数据的可靠性和持久性是非常重要的。 分布式支持:Redis 支持分布式部署,可以搭建多个 Redis 节点组成集群,实现数据的分片和负载均衡,提高了系统的扩展性和容错性。 生态系统丰富:Redis 有一个活跃的开源社区,提供了许多与 Spring 集成的库和工具,如 Spring Data Redis、Lettuce 和 Redisson 等,这些工具可以方便地与 Spring Cache 集成,简化了开发和配置的过程。 综上所述,Redis 在性能、数据结构、持久化、分布式支持以及生态系统方面的优势,使其成为 Spring Cache 中最常用的缓存实现之一。
本文将会指导你如何在 Spring Boot 中整合 Spring Cache 和 Redis 来开发缓存应用,并且修改其序列化方式为 JSON。
本文中使用的软件版本:
spring boot:3.1.3 redis:7.0.5 2、整合 Spring Cache 你可以点击 start.springboot.io 快速地创建此演示项目。
项目的依赖如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!
Spring Profiles 简介 通常,软件应用程序会在不同的环境中运行。在开发过程中,它将在 local 环境运行,然后我们可能会将它部署到 QA、Staging、Performance 环境中,最后再部署到 Production 环境中。在不同环境中运行应用程序时,你可能需要用不同的配置属性来配置应用程序。
例如,如果你使用了数据库,那么你可以在开发过程中将数据库连接属性配置为本地运行的数据库。在 QA、Staging、Performance 和 Production 环境中部署时,则需要将数据库属性配置为特定环境的数据库。
Spring 为 application properties 的外部化提供了强大的支持,因此我们可以在不同的环境中运行时配置不同的属性。
为了使其更简单,我们可以使用 Spring Profiles 机制。使用不同的 profile 来配置 application properties,然后根据需要启用所需的 profile。
使用 properties 配置 Profile 假设我们正在构建一个使用 PostgreSQL 数据库的 Spring Boot 应用程序。我们希望在本地运行应用程序,使用在笔记本电脑上运行的 PostgreSQL 数据库。此外,我们还希望将应用程序部署到 QA 和 Production 环境中。
我们可以在默认的 properties 文件 src/main/resources/application.properties 中配置默认属性,如下所示:
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres spring.datasource.username=postgres spring.datasource.password=postgres 我们可以在 src/main/resources/application-{profile}.{properties/yml} 文件中配置任何特定 profile 的属性,当你激活该 profile 时,Spring Boot 会自动使用该 profile 的属性。因此,我们可以按照以下方式在 src/main/resources/application-qa.properties 中配置 QA profile 的属性:
spring.datasource.url=jdbc:postgresql://postgres_qa:5432/postgres spring.
Spring Data JPA 是 Spring 框架提供的一个模块,用于简化与关系型数据库的交互和数据访问。它基于JPA(Java Persistence API)标准,并提供了一组易于使用的API和工具,帮助开发人员更轻松地进行数据库操作。通过Spring Data JPA,开发人员可以通过编写简洁的代码来执行常见的 CRUD 操作,同时还支持高级查询、分页、事务管理等功能。它的目标是提供一种更简单、更高效的方式来处理数据库操作,减少开发人员的工作量,并提高应用程序的可维护性和可扩展性。
本文将会指导你如何在 Spring Boot 应用中整合、使用 Spring Data Jpa。
软件版本:
Java:17 Spring Boot:3.1.3 MySQL:8.0.27 创建工程 点击 start.springboot.io 快速创建 Spring Boot 整合 Spring Data Jpa 的示例应用。
我们选择了 spring-boot-starter-web、spring-boot-starter-data-jpa、mysql-connector-j 和 spring-boot-starter-test 依赖。
pom.xml 如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> spring-boot-starter-data-jpa 默认使用 Hibernate 作为 JPA 实现。本文使用 MYSQL 数据库进行演示,如果你使用其他数据库需要修改驱动。
1、概览 当我们在 IDE 中运行代码分析工具时,它可能会对带有 @Autowired 注解的字段发出 “Field injection is not recommended” 的警告。
在本教程中,我们将探讨为什么不推荐字段注入,以及我们可以使用哪些替代方法。
2、依赖注入(DI) 依赖注入是一种设计模式,用于管理对象之间的依赖关系。它通过外部容器提供对象的依赖,使得对象之间的关系更加灵活、可配置和可测试。依赖注入提高了代码的可维护性、可测试性和可扩展性。它是 Spring 框架的核心功能之一。
我们可以通过三种方式注入依赖对象,即:
构造函数注入。 Setter 方法注入。 字段注入。 第三种方法是使用 @Autowired 注解将依赖直接注入类中。虽然这可能是最简单的方法,但它可能会导致一些潜在的问题。
更重要的是,即使是在 Spring 的官方文档 中,也不再介绍字段注入。
3、Null 安全 让我们定义 EmailService 类并使用字段注入 EmailValidator 依赖:
@Service public class EmailService { @Autowired private EmailValidator emailValidator; } 现在,让我们添加 process() 方法:
public void process(String email) { if(!emailValidator.isValid(email)){ throw new IllegalArgumentException(INVALID_EMAIL); } // ... } 我们可以使用默认构造函数直接创建 EmailService 实例。但只有在提供了 EmailValidator 依赖的情况下,EmailService 才能正常工作。
EmailService emailService = new EmailService(); emailService.