Spring Boot集成了许多数据技术,包括SQL和NoSQL。

1. SQL Databases

Spring框架为使用SQL数据库提供了广泛的支持,从使用JdbcTemplate的直接JDBC访问到完成Hibernate等“对象关系映射”技术。Spring data提供了额外级别的功能:直接从接口创建Repository实现,并使用约定从方法名生成查询。

1.1. Configure a DataSource

Java的javax.sql.DataSource接口提供了使用数据库连接的标准方法。传统上,“数据源”使用URL和一些凭据来建立数据库连接。

See the “How-to” section for more advanced examples, typically to take full control over the configuration of the DataSource.

1.1.1. Embedded Database Support

使用内存中的嵌入式数据库开发应用程序通常很方便。显然,内存中的数据库不提供持久存储。您需要在应用程序启动时填充数据库,并准备好在应用程序结束时丢弃数据。

The “How-to” section includes a section on how to initialize a database.

Spring Boot可以自动配置嵌入式h2HSQLDerby数据库。您不需要提供任何连接URL。您只需要包括对要使用的嵌入式数据库的构建依赖项。如果类路径上有多个嵌入式数据库,请设置spring.datasource.embedded-database-connection配置属性以控制使用哪个数据库。将该属性设置为None将禁用嵌入式数据库的自动配置。

如果您在测试中使用此功能,您可能会注意到,无论您使用了多少应用程序上下文,整个测试套件都会重用相同的数据库。如果希望确保每个上下文都有单独的嵌入式数据库,则应该将spring.datasource.generate-unique-name设置为TRUE

例如,典型的POM依赖关系如下所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>
             
             
You need a dependency on spring-jdbc for an embedded database to be auto-configured. In this example, it is pulled in transitively through spring-boot-starter-data-jpa.
If, for whatever reason, you do configure the connection URL for an embedded database, take care to ensure that the database’s automatic shutdown is disabled. If you use H2, you should use DB_CLOSE_ON_EXIT=FALSE to do so. If you use HSQLDB, you should ensure that shutdown=true is not used. Disabling the database’s automatic shutdown lets Spring Boot control when the database is closed, thereby ensuring that it happens once access to the database is no longer needed.

1.1.2. Connection to a Production Database

还可以使用池化数据源自动配置生产数据库连接。

1.1.3. DataSource Configuration

数据源配置由spring.datource.*中的外部配置属性控制。例如,您可以在Applation.Properties中声明以下部分:

Properties
Yaml
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
             
             
You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database.
Spring Boot can deduce the JDBC driver class for most databases from the URL. If you need to specify a specific class, you can use the spring.datasource.driver-class-name property.
For a pooling DataSource to be created, we need to be able to verify that a valid Driver class is available, so we check for that before doing anything. In other words, if you set spring.datasource.driver-class-name=com.mysql.jdbc.Driver, then that class has to be loadable.

有关更多受支持的选项,请参阅DataSourceProperties。这些是无论实际实现如何都有效的标准选项。还可以通过使用它们各自的前缀(spring.datource.hikari.*spring.datource.tomcat.*spring.datource.dbcp2..*spring.datource.oracleucp.*)来微调特定于实现的设置。有关详细信息,请参阅您正在使用的连接池实现的文档。

例如,如果您使用Tomcat连接池,则可以定制许多附加设置,如下例所示:

Properties
Yaml
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true
             
             

这会将池设置为等待10000ms,然后在没有可用连接的情况下引发异常,将最大连接数限制为50,并在从池借用连接之前验证连接。

1.1.4. Supported Connection Pools

Spring Boot使用以下算法来选择特定实现:

  1. 我们更喜欢HikariCP的性能和并发性。如果HikariCP可用,我们总是选择它。

  2. 否则,如果Tomcat池DataSource可用,我们将使用它。

  3. 否则,如果Commons DBCP2可用,我们将使用它。

  4. 如果HikariCP、Tomcat和DBCP2都不可用,并且Oracle UCP可用,我们将使用它。

If you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpa “starters”, you automatically get a dependency to HikariCP.

您可以完全绕过该算法,并通过设置spring.datource.type属性来指定要使用的连接池。如果在Tomcat容器中运行应用程序,这一点尤其重要,因为默认情况下会提供tomcat-jdbc

其他连接池始终可以使用DataSourceBuilder手动配置。如果您定义自己的DataSourceBean,则不会发生自动配置。DataSourceBuilder支持以下连接池:

  • HikariCP

  • Tomcat池化数据源

  • 公有DBCP2

  • Oracle UCP&;OracleDataSource

  • Spring框架的SimpleDriverDataSource

  • H2JdbcDataSource

  • PostgreSQLPGSimpleDataSource

  • C3P0

1.1.5. Connection to a JNDI DataSource

如果将Spring Boot应用程序部署到应用程序服务器,您可能希望使用应用程序服务器的内置功能配置和管理数据源,并使用JNDI访问它。

spring.datource.jndi-name属性可以用作spring.Dataource.urlspring.Dataource.usernamespring.Dataource.password属性的替代,以便从特定的JNDI位置访问DataSource。例如,Applation.Properties中的以下部分显示了如何访问已定义的JBossDataSource

Properties
Yaml
spring.datasource.jndi-name=java:jboss/datasources/customers
             
             

1.2. Using JdbcTemplate

Spring的JdbcTemplateNamed参数JdbcTemplate类是自动配置的,您可以将它们直接放入您自己的Bean中,如下例所示:

Java
Kotlin
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final JdbcTemplate jdbcTemplate; public MyBean(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void doSomething() { this.jdbcTemplate ... } } 
            
            

您可以使用spring.jdbc.template.*属性来自定义模板的一些属性,如下例所示:

Properties
Yaml
spring.jdbc.template.max-rows=500
            
            
The NamedParameterJdbcTemplate reuses the same JdbcTemplate instance behind the scenes. If more than one JdbcTemplate is defined and no primary candidate exists, the NamedParameterJdbcTemplate is not auto-configured.

1.3. JPA and Spring Data JPA

Java持久性API是一种允许您将对象“映射”到关系数据库的标准技术。SpringBoot-starter-data-jpaPOM提供了一种快速入门的方法。它提供以下关键依赖项:

  • Hibernate:最流行的JPA实现之一。

  • Spring data JPA:帮助您实现基于JPA的存储库。

  • Spring ORM:来自Spring框架的核心ORM支持。

We do not go into too many details of JPA or Spring Data here. You can follow the “Accessing Data with JPA” guide from spring.io and read the Spring Data JPA and Hibernate reference documentation.

1.3.1. Entity Classes

传统上,JPA“实体”类是在sistence.xml文件中指定的。对于Spring Boot,这个文件不是必需的,而是使用“实体扫描”。默认情况下,搜索主配置类(用@EnableAutoConfiguration@SpringBootApplication注释的包)下的所有包。

使用@Entity@Embeddable@MappdSuperclass注释的任何类都会被考虑。典型的实体类类似于以下示例:

Java
Kotlin
import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @Entity public class City implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String state; // ... additional members, often include @OneToMany mappings protected City() { // no-args constructor required by JPA spec // this one is protected since it should not be used directly } public City(String name, String state) { this.name = name; this.state = state; } public String getName() { return this.name; } public String getState() { return this.state; } // ... etc } 
             
             
You can customize entity scanning locations by using the @EntityScan annotation. See the “howto.html” how-to.

1.3.2. Spring Data JPA Repositories

Spring data JPA存储库是您可以定义来访问数据的接口。JPA查询是根据方法名称自动创建的。例如,CityRepository接口可能声明一个findAllByState(字符串状态)方法来查找给定州的所有城市。

对于更复杂的查询,您可以使用Spring data的查询注释来注释您的方法。

Spring数据存储库通常从CrudRepository接口扩展。如果您使用自动配置,将从包含您的主配置类(用@EnableAutoConfiguration@SpringBootApplication注释的那个类)的包中搜索存储库。

以下示例显示了一个典型的Spring数据存储库接口定义:

Java
Kotlin
import org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses.City; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.Repository; public interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); City findByNameAndStateAllIgnoringCase(String name, String state); } 
             
             

Spring data JPA存储库支持三种不同的引导模式:默认、延迟和延迟。要启用延迟或延迟引导,请将spring.data.jpa.repositories.bootstrap-mode属性分别设置为<代码>延迟 或<代码>延迟 。在使用延迟或延迟引导时,自动配置的EntityManagerFactoryBuilder将使用上下文的AsyncTaskExecutor作为引导执行器。如果存在多个,将使用名为ApplationTaskExecutor的那个。

在使用延迟或延迟引导时,请确保在应用程序上下文引导阶段之后推迟对JPA基础设施的任何访问。您可以使用SmartInitializingSingleton调用任何需要JPA基础设施的初始化。对于创建为SpringBean的JPA组件(如转换器),使用ObjectProvider延迟依赖项的解析(如果有的话)。

We have barely scratched the surface of Spring Data JPA. For complete details, see the Spring Data JPA reference documentation.

1.3.3. Spring Data Envers Repositories

如果Spring data enver可用,则JPA存储库将自动配置为支持典型的enver查询。

要使用Spring Data enver,请确保您的存储库从RevisionRepository扩展,如下例所示:

Java
Kotlin
import org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses.Country; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.Repository; import org.springframework.data.repository.history.RevisionRepository; public interface CountryRepository extends RevisionRepository<Country, Long, Integer>, Repository<Country, Long> { Page<Country> findAll(Pageable pageable); } 
             
             
For more details, check the Spring Data Envers reference documentation.

1.3.4. Creating and Dropping JPA Databases

默认情况下,仅当您使用嵌入式数据库(H2、HSQL或Derby)时,才会自动创建JPA数据库。您可以使用spring.jpa.*属性显式配置JPA设置。例如,要创建和删除表,您可以在应用程序中添加以下行。属性

Properties
Yaml
spring.jpa.hibernate.ddl-auto=create-drop
             
             
Hibernate’s own internal property name for this (if you happen to remember it better) is hibernate.hbm2ddl.auto. You can set it, along with other Hibernate native properties, by using spring.jpa.properties.* (the prefix is stripped before adding them to the entity manager). The following line shows an example of setting JPA properties for Hibernate:
Properties
Yaml
spring.jpa.properties.hibernate[globally_quoted_identifiers]=true
             
             

上一示例中的行将hibernate.globally_quoted_identifiers属性的<代码>TRUE值传递给Hibernate实体管理器。

默认情况下,DDL执行(或验证)将推迟到ApplicationContext启动。还有一个spring.jpa.Generate-ddl标志,但如果Hibernate自动配置处于活动状态,则不会使用它,因为ddl-auto设置更细粒度。

1.3.5. Open EntityManager in View

如果您正在运行Web应用程序,Spring Boot在默认情况下注册OpenEntityManagerInViewInterceptor以应用“Open EntiyManager in View”模式,以允许在Web视图中进行延迟加载。如果您不想要此行为,则应在应用程序.Properties中将spring.jpa.Open-in-view设置为False

1.4. Spring Data JDBC

Spring Data包括对JDBC的存储库支持,并将为CrudRepository上的方法自动生成SQL。对于更高级的查询,提供了@Query注释。

当必要的依赖项位于类路径上时,Spring Boot将自动配置Spring data的JDBC存储库。可以将它们添加到您的项目中,只需对Spring-Boot-starter-data-jdbc进行一次依赖。如有必要,您可以通过向应用程序添加@EnableJdbcRepositories注释或JdbcConfiguration子类来控制Spring data JDBC的配置。

For complete details of Spring Data JDBC, see the reference documentation.

1.5. Using H2’s Web Console

H2数据库提供了一个基于浏览器控制台,Spring Boot可以为您自动配置。当满足以下条件时,将自动配置控制台:

If you are not using Spring Boot’s developer tools but would still like to make use of H2’s console, you can configure the spring.h2.console.enabled property with a value of true.
The H2 console is only intended for use during development, so you should take care to ensure that spring.h2.console.enabled is not set to true in production.

1.5.1. Changing the H2 Console’s Path

默认情况下,控制台位于/h2-控制台。您可以使用spring.h2.console.Path属性来自定义控制台的路径。

1.5.2. Accessing the H2 Console in a Secured Application

H2控制台使用框架,由于它仅用于开发,因此不实施CSRF保护措施。如果您的应用程序使用了Spring Security,则需要将其配置为

  • 禁用针对控制台的请求的CSRF保护,

  • 在来自控制台的响应中,将标题X-Frame-Options设置为SAMEORIGIN

关于CSRF和头文件X-Frame-Options的更多信息可以在Spring Security Reference Guide中找到。

在简单的设置中,可以使用如下SecurityFilterChain

Java
Kotlin
import org.springframework.boot.autoconfigure.security.servlet.PathRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Profile("dev") @Configuration(proxyBeanMethods = false) public class DevProfileSecurityConfiguration { @Bean @Order(Ordered.HIGHEST_PRECEDENCE) SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception { http.securityMatcher(PathRequest.toH2Console()); http.authorizeHttpRequests(yourCustomAuthorization()); http.csrf((csrf) -> csrf.disable()); http.headers((headers) -> headers.frameOptions().sameOrigin()); return http.build(); } } 
             
             
The H2 console is only intended for use during development. In production, disabling CSRF protection or allowing frames for a website may create severe security risks.
PathRequest.toH2Console() returns the correct request matcher also when the console’s path has been customized.

1.6. Using jOOQ

JOOQ面向对象查询(jOOQ)是data geekery的一个流行产品,它从您的数据库生成Java代码,并允许您通过其流畅的API构建类型安全的SQL查询。商业版和开源版都可以与Spring Boot一起使用。

1.6.1. Code Generation

为了使用jOOQ类型安全查询,您需要从数据库模式生成Java类。您可以按照jOOQ用户手册中的说明操作。如果您使用jooq-codegen-maven插件,并且还使用Spring-ot-starter-parent“父POM”,则可以安全地省略该插件的<;版本&标记。您还可以使用Spring Boot定义的版本变量(如h2.version)来声明插件的数据库依赖关系。下面的清单显示了一个示例:

<plugin>
    <groupId>org.jooq</groupId>
    <artifactId>jooq-codegen-maven</artifactId>
    <executions>
        ...
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
        </dependency>
    </dependencies>
    <configuration>
        <jdbc>
            <driver>org.h2.Driver</driver>
            <url>jdbc:h2:~/yourdatabase</url>
        </jdbc>
        <generator>
            ...
        </generator>
    </configuration>
</plugin>
             
             

1.6.2. Using DSLContext

JOOQ提供的流畅接口通过org.jooq.DSLContext接口发起。Spring Boot自动将DSLContext配置为Spring Bean,并将其连接到您的应用程序DataSource。要使用DSLContext,可以注入它,如下例所示:

Java
Kotlin
import java.util.GregorianCalendar; import java.util.List; import org.jooq.DSLContext; import org.springframework.stereotype.Component; import static org.springframework.boot.docs.data.sql.jooq.dslcontext.Tables.AUTHOR; @Component public class MyBean { private final DSLContext create; public MyBean(DSLContext dslContext) { this.create = dslContext; } } 
             
             
The jOOQ manual tends to use a variable named create to hold the DSLContext.

然后,您可以使用DSLContext构造查询,如下例所示:

Java
Kotlin
public List<GregorianCalendar> authorsBornAfter1980() {
    return this.create.selectFrom(AUTHOR)
            .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1)))
            .fetch(AUTHOR.DATE_OF_BIRTH);

             
             

1.6.3. jOOQ SQL Dialect

除非配置了spring.jooq.sql-方言属性,否则Spring Boot将确定要用于数据源的SQL方言。如果Spring Boot无法检测到该方言,它将使用默认

Spring Boot can only auto-configure dialects supported by the open source version of jOOQ.

1.6.4. Customizing jOOQ

可以通过定义您自己的DefaultConfigurationCustomizerBean来实现更高级的定制,该Bean将在创建org.jooq.Configuration@Bean之前被调用。这优先于自动配置应用的任何内容。

如果希望完全控制jOOQ配置,还可以创建自己的org.jooq.Configuration@Bean

1.7. Using R2DBC

反应式关系数据库连接(R2DBC)项目为关系数据库带来了反应式编程API。R2DBC的io.r2dbc.Spi.Connection提供了使用非阻塞数据库连接的标准方法。使用ConnectionFactory提供连接,类似于使用JDBC的DataSource

ConnectionFactory配置由spring.r2dbc.*中的外部配置属性控制。例如,您可以在Applation.Properties中声明以下部分:

Properties
Yaml
spring.r2dbc.url=r2dbc:postgresql://localhost/test
spring.r2dbc.username=dbuser
spring.r2dbc.password=dbpass
            
            
You do not need to specify a driver class name, since Spring Boot obtains the driver from R2DBC’s Connection Factory discovery.
At least the url should be provided. Information specified in the URL takes precedence over individual properties, that is name, username, password and pooling options.
The “How-to” section includes a section on how to initialize a database.

要定制由ConnectionFactory创建的连接,即设置您不想(或不能)在中央数据库配置中配置的特定参数,您可以使用ConnectionFactoryOptionsBuilderCustomizer@Bean。以下示例显示如何在其余选项取自应用程序配置时手动覆盖数据库端口:

Java
Kotlin
import io.r2dbc.spi.ConnectionFactoryOptions; import org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryOptionsBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyR2dbcConfiguration { @Bean public ConnectionFactoryOptionsBuilderCustomizer connectionFactoryPortCustomizer() { return (builder) -> builder.option(ConnectionFactoryOptions.PORT, 5432); } } 
            
            

以下示例显示如何设置一些PostgreSQL连接选项:

Java
Kotlin
import java.util.HashMap; import java.util.Map; import io.r2dbc.postgresql.PostgresqlConnectionFactoryProvider; import org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryOptionsBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyPostgresR2dbcConfiguration { @Bean public ConnectionFactoryOptionsBuilderCustomizer postgresCustomizer() { Map<String, String> options = new HashMap<>(); options.put("lock_timeout", "30s"); options.put("statement_timeout", "60s"); return (builder) -> builder.option(PostgresqlConnectionFactoryProvider.OPTIONS, options); } } 
            
            

ConnectionFactoryBean可用时,常规的JDBCDataSource自动配置将退出。如果您希望保留JDBC数据源自动配置,并对在反应式应用程序中使用阻塞JDBC API的风险感到满意,请在应用程序中的@Configuration类上添加@Import(DataSourceAutoConfiguration.class)以重新启用它。

1.7.1. Embedded Database Support

JDBC支持类似,Spring Boot可以自动配置嵌入式数据库以供被动使用。您不需要提供任何连接URL。您只需包括要使用的嵌入式数据库的构建依赖项,如下例所示:

<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-h2</artifactId>
    <scope>runtime</scope>
</dependency>
             
             

如果您在测试中使用此功能,您可能会注意到,无论您使用了多少应用程序上下文,整个测试套件都会重用相同的数据库。如果希望确保每个上下文都有单独的嵌入式数据库,则应该将spring.r2dbc.generate-unique-name设置为TRUE

1.7.2. Using DatabaseClient

自动配置一个DatabaseClientBean,您可以将其@AuTower直接放入您自己的Bean中,如下例所示:

Java
Kotlin
import java.util.Map; import reactor.core.publisher.Flux; import org.springframework.r2dbc.core.DatabaseClient; import org.springframework.stereotype.Component; @Component public class MyBean { private final DatabaseClient databaseClient; public MyBean(DatabaseClient databaseClient) { this.databaseClient = databaseClient; }  // ...  public Flux<Map<String, Object>> someMethod() { return this.databaseClient.sql("select * from user").fetch().all(); } } 
             
             

1.7.3. Spring Data R2DBC Repositories

Spring data R2DBC存储库是您可以定义来访问数据的接口。根据您的方法名称自动创建查询。例如,CityRepository接口可能声明一个findAllByState(字符串状态)方法来查找给定州的所有城市。

对于更复杂的查询,您可以使用Spring data的查询注释来注释您的方法。

Spring数据存储库通常从CrudRepository接口扩展。如果您使用自动配置,将从包含您的主配置类(用@EnableAutoConfiguration@SpringBootApplication注释的那个类)的包中搜索存储库。

以下示例显示了一个典型的Spring数据存储库接口定义:

Java
Kotlin
import reactor.core.publisher.Mono; import org.springframework.data.repository.Repository; public interface CityRepository extends Repository<City, Long> { Mono<City> findByNameAndStateAllIgnoringCase(String name, String state); } 
             
             
We have barely scratched the surface of Spring Data R2DBC. For complete details, see the Spring Data R2DBC reference documentation.

2. Working with NoSQL Technologies

Spring Data提供了其他项目,帮助您访问各种NoSQL技术,包括:

Spring Boot为Redis、MongoDB、Neo4j、Elasticearch、Cassandra、Couchbase、LDAP和InfluxDB提供自动配置。此外,Spring Boot for ApacheGeode提供了自动配置。您可以使用其他项目,但您必须自己配置它们。参阅相应的参考文档,网址为spring.io/projects/spring-data.

2.1. Redis

Redis是一个缓存、消息代理和功能丰富的键值存储。Spring Boot为lettuceJedis客户端库以及由Spring data Redis提供的抽象提供了基本的自动配置。

有一个SpringBoot-starter-data-redis“starter”,用于以方便的方式收集依赖项。默认情况下,它使用lettuce。这种初学者既可以处理传统应用程序,也可以处理被动应用程序。

We also provide a spring-boot-starter-data-redis-reactive “Starter” for consistency with the other stores with reactive support.

2.1.1. Connecting to Redis

您可以像注入任何其他Spring Bean一样注入自动配置的RedisConnectionFactoryStringRedisTemplate或普通RedisTemplate实例。默认情况下,该实例尝试连接到位于localhost:6379的Redis服务器。下面的清单显示了这样一个Bean的示例:

Java
Kotlin
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final StringRedisTemplate template; public MyBean(StringRedisTemplate template) { this.template = template; }  // ...  public Boolean someMethod() { return this.template.hasKey("spring"); } } 
             
             
You can also register an arbitrary number of beans that implement LettuceClientConfigurationBuilderCustomizer for more advanced customizations. ClientResources can also be customized using ClientResourcesBuilderCustomizer. If you use Jedis, JedisClientConfigurationBuilderCustomizer is also available. Alternatively, you can register a bean of type RedisStandaloneConfiguration, RedisSentinelConfiguration, or RedisClusterConfiguration to take full control over the configuration.

如果添加您自己的任何自动配置类型的@Bean,它将替换缺省值(除了RedisTemplate,当排除是基于Bean名称、redisTemplate而不是它的类型时)。

默认情况下,如果类路径上有Commons-pool2,则会自动配置池连接工厂。

2.2. MongoDB

MongoDB是一个开源的NoSQL文档数据库,它使用类似JSON的模式,而不是传统的基于表的关系数据。Spring Boot为使用MongoDB提供了几个便利,包括<spring-boot-starter-data-mongodb-reactive>Spring-Boot-starter-data-mongoDB和Spring“starters”。

2.2.1. Connecting to a MongoDB Database

要访问MongoDB数据库,您可以注入一个自动配置的org.springframework.data.mongodb.MongoDatabaseFactory.默认情况下,该实例尝试连接到位于mongodb://localhost/test的MongoDB服务器。以下示例说明如何连接到MongoDB数据库:

Java
Kotlin
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.stereotype.Component; @Component public class MyBean { private final MongoDatabaseFactory mongo; public MyBean(MongoDatabaseFactory mongo) { this.mongo = mongo; }  // ...  public MongoCollection<Document> someMethod() { MongoDatabase db = this.mongo.getMongoDatabase(); return db.getCollection("users"); } } 
             
             

如果您已经定义了自己的MongoClient,它将被用来自动配置合适的MongoDatabaseFactory

自动配置的MongoClient是使用MongoClientSettingBean创建的。如果您已经定义了自己的MongoClientSetting,则无需修改即可使用,spring.data.mongob属性将被忽略。否则,将自动配置MongoClientSetting,并对其应用spring.data.mongob属性。在任何一种情况下,您都可以声明一个或多个代码Bean来微调<MongoClientSettingsBuilderCustomizer>MongoClientSetting配置。每个调用都将与用于构建MongoClientSettings.BuilderMongoClientSettings.Builder一起顺序调用。

您可以设置spring.data.mongob.uri属性以更改URL并配置其他设置,如副本集,如下例所示:

Properties
Yaml
spring.data.mongodb.uri=mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/test
             
             

或者,您可以使用离散属性指定连接详细信息。例如,您可以在应用程序中声明以下设置。属性

Properties
Yaml
spring.data.mongodb.host=mongoserver1.example.com
spring.data.mongodb.port=27017
spring.data.mongodb.additional-hosts[0]=mongoserver2.example.com:23456
spring.data.mongodb.database=test
spring.data.mongodb.username=user
spring.data.mongodb.password=secret
             
             

如果未指定spring.data.mongob.port,则使用默认值27017。您可以从前面显示的示例中删除此行。

您还可以使用host:port语法将端口指定为主机地址的一部分。如果您需要更改附加主机条目的端口,则应使用此格式。

If you do not use Spring Data MongoDB, you can inject a MongoClient bean instead of using MongoDatabaseFactory. If you want to take complete control of establishing the MongoDB connection, you can also declare your own MongoDatabaseFactory or MongoClient bean.
If you are using the reactive driver, Netty is required for SSL. The auto-configuration configures this factory automatically if Netty is available and the factory to use has not been customized already.

2.2.2. MongoTemplate

Spring data MongoDB提供了一个MongoTemplate类,该类在设计上与Spring的JdbcTemplate非常相似。与JdbcTemplate一样,Spring Boot会自动配置一个Bean来注入模板,如下所示:

Java
Kotlin
import com.mongodb.client.MongoCollection; import org.bson.Document; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final MongoTemplate mongoTemplate; public MyBean(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; }  // ...  public MongoCollection<Document> someMethod() { return this.mongoTemplate.getCollection("users"); } } 
             
             

有关完整信息,请参阅MongoOperationsJavadoc

2.2.3. Spring Data MongoDB Repositories

Spring Data包含对MongoDB的存储库支持。与前面讨论的JPA存储库一样,基本原则是基于方法名称自动构造查询。

事实上,Spring data JPA和Spring data MongoDB共享相同的公共基础设施。您可以采用前面的JPA示例,并假设City现在是一个MongoDB数据类,而不是JPA@Entity,它的工作方式相同,如下例所示:

Java
Kotlin
import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.Repository; public interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); City findByNameAndStateAllIgnoringCase(String name, String state); } 
             
             
You can customize document scanning locations by using the @EntityScan annotation.
For complete details of Spring Data MongoDB, including its rich object mapping technologies, see its reference documentation.

2.3. Neo4j

Neo4j是一个开源的NoSQL图形数据库,它使用了由一级关系连接的节点的丰富数据模型,比传统的RDBMS方法更适合连接的大数据。Spring Boot为使用Neo4j提供了几个便利,包括Spring-boot-starter-data-new 4j“starter”。

2.3.1. Connecting to a Neo4j Database

要访问Neo4j服务器,您可以注入一个自动配置的org.ne4j.driver.Driver。默认情况下,该实例尝试使用Bolt协议连接到位于localhost:7687的Neo4j服务器。以下示例显示如何注入Neo4j驱动程序,该驱动程序允许您访问会话

Java
Kotlin
import org.neo4j.driver.Driver; import org.neo4j.driver.Session; import org.neo4j.driver.Values; import org.springframework.stereotype.Component; @Component public class MyBean { private final Driver driver; public MyBean(Driver driver) { this.driver = driver; }  // ...  public String someMethod(String message) { try (Session session = this.driver.session()) { return session.executeWrite((transaction) -> transaction .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)", Values.parameters("message", message)) .single().get(0).asString()); } } } 
             
             

您可以使用spring.ne4j.*属性配置驱动程序的各个方面。以下示例显示如何配置要使用的URI和凭据:

Properties
Yaml
spring.neo4j.uri=bolt://my-server:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=secret
             
             

自动配置的驱动程序使用ConfigBuilder创建。若要微调其配置,请声明一个或多个ConfigBuilderCustomizerBean。它们将与用于构建驱动程序ConfigBuilder一起顺序调用。

2.3.2. Spring Data Neo4j Repositories

Spring Data包括对Neo4j的存储库支持。有关Spring data Neo4j的完整细节,请参阅参考文档

与许多其他Spring数据模块一样,Spring data Neo4j与Spring data JPA共享公共基础设施。您可以采用前面的JPA示例,并将City定义为Spring data Neo4j@Node,而不是JPA@Entity,存储库抽象的工作方式相同,如下例所示:

Java
Kotlin
import java.util.Optional; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface CityRepository extends Neo4jRepository<City, Long> { Optional<City> findOneByNameAndState(String name, String state); } 
             
             

SpringBoot-starter-data-ne4j“starter”启用存储库支持和事务管理。Spring Boot使用Neo4jTemplateReactive Neo4jTemplateBean同时支持经典和反应式Neo4j存储库。当类路径上有Project Reader可用时,也会自动配置反应样式。

您可以通过在@configuration-Bean上分别使用@EnableNeo4jRepositories@EntityScan来自定义查找存储库和实体的位置。

在使用反应式样式的应用程序中,不会自动配置Reactive TransactionManager。要启用事务管理,必须在配置中定义以下Bean:

Java
Kotlin
import org.neo4j.driver.Driver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider; import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager; @Configuration(proxyBeanMethods = false) public class MyNeo4jConfiguration { @Bean public ReactiveNeo4jTransactionManager reactiveTransactionManager(Driver driver, ReactiveDatabaseSelectionProvider databaseNameProvider) { return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider); } } 
                  
                  

2.4. Elasticsearch

Elasticearch是一个开源、分布式、REST风格的搜索和分析引擎。Spring Boot为Elasticearch客户端提供基本的自动配置。

Spring Boot支持多个客户端:

  • 官方低级REST客户端

  • 官方Java API客户端

  • 由Spring Data Elasticearch提供的Reactive Elasticearch Client

Spring Boot提供了一个专用的“启动器”,spring-boot-starter-data-elasticsearch.

2.4.1. Connecting to Elasticsearch Using REST clients

ElasticSearch附带了两个可用于查询集群的不同REST客户端:来自org.elasticsearch.client:elasticsearch-rest-client模块的低级客户端和来自co.elastic.clients:elasticsearch-java模块的Java API客户端。此外,Spring Boot从org.springframework.data:spring-data-elasticsearch模块提供了对反应式客户端的支持。默认情况下,客户端将以Localhost:9200为目标。您可以使用spring.elasticearch.*属性进一步调整客户端的配置方式,如下例所示:

Properties
Yaml
spring.elasticsearch.uris=https://search.example.com:9200
spring.elasticsearch.socket-timeout=10s
spring.elasticsearch.username=user
spring.elasticsearch.password=secret
             
             
Connecting to Elasticsearch Using RestClient

如果类路径上有ElasticSearch-Rest-Client,则Spring Boot将自动配置并注册RestClientBean。除了前面描述的属性之外,要对RestClient进行微调,您可以注册任意数量的实现RestClientBuilderCustomizer的Bean,以实现更高级的定制。要完全控制客户端的配置,请定义一个RestClientBuilderBean。

此外,如果elasticsearch-rest-client-sniffer位于类路径上,嗅探器将自动配置为自动从正在运行的Elasticearch集群中发现节点,并将它们设置在RestClientBean上。您可以进一步调整嗅探器的配置方式,如下例所示:

Properties
Yaml
spring.elasticsearch.restclient.sniffer.interval=10m
spring.elasticsearch.restclient.sniffer.delay-after-failure=30s
              
              
Connecting to Elasticsearch Using ElasticsearchClient

如果类路径上有co.elastic.clients:elasticsearch-java,Spring Boot将自动配置并注册Elasticearch ClientBean。

Elasticearch Client使用依赖于前面描述的RestClient的传输。因此,前面描述的属性可用于配置Elasticearch Client。此外,您可以定义一个TransportOptionsBean来进一步控制传输的行为。

Connecting to Elasticsearch using ReactiveElasticsearchClient

Spring data Elasticearch提供了Reactive Elasticearch Client,用于以被动方式查询Elasticearch实例。如果类路径上有Spring data Elasticearch和Reactive,则Spring Boot将自动配置并注册一个Reactive Elasticearch Client

Reactive Elasticearch客户端使用依赖于前面描述的RestClient的传输。因此,可以使用前面描述的属性来配置Reactive Elasticearch Client。此外,您可以定义一个TransportOptionsBean来进一步控制传输的行为。

2.4.2. Connecting to Elasticsearch by Using Spring Data

要连接到Elasticearch,必须定义一个Elasticearch ClientBean,由Spring Boot自动配置或由应用程序手动提供(请参阅前面的小节)。有了这个配置后,就可以像注入任何其他Spring Bean一样注入Elasticearch模板,如下例所示:

Java
Kotlin
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final ElasticsearchTemplate template; public MyBean(ElasticsearchTemplate template) { this.template = template; }  // ...  public boolean someMethod(String id) { return this.template.exists(id, User.class); } } 
             
             

在有了Spring-data-Elasticearch和Reader的情况下,Spring Boot还可以将一个Reactive Elasticearch Client和一个Reactive Elasticearch Template自动配置为Bean。它们是其他REST客户端的被动等价物。

2.4.3. Spring Data Elasticsearch Repositories

Spring Data包括对Elasticearch的存储库支持。与前面讨论的JPA存储库一样,基本原则是根据方法名称自动构造查询。

事实上,Spring data JPA和Spring data Elasticearch共享相同的公共基础设施。您可以采用前面的JPA示例,并假设City现在是一个Elasticearch@Document类,而不是JPA@Entity,它的工作方式相同。

For complete details of Spring Data Elasticsearch, see the reference documentation.

Spring Boot使用Elasticearch RestTemplateReactive Elasticearch TemplateBean同时支持传统和反应式Elasticearch存储库。如果存在所需的依赖关系,这些Bean很可能是由Spring Boot自动配置的。

如果您希望使用您自己的模板来支持Elasticearch存储库,您可以添加您自己的Elasticearch RestTemplateElasticearch Operations@Bean,只要它被命名为“弹性搜索模板”。同样的情况也适用于Reactive Elasticearch TemplateReactive Elasticearch Operations,其Bean名称为“reactive Elasticearch Template”

您可以选择使用以下属性禁用资料库支持:

Properties
Yaml
spring.data.elasticsearch.repositories.enabled=false
             
             

2.5. Cassandra

Cassandra是一个开源的分布式数据库管理系统,旨在跨许多商用服务器处理大量数据。Spring Boot为Cassandra以及由Spring data Cassandra提供的抽象提供了自动配置。有一个spring-boot-starter-data-cassandra“启动器”可以方便地收集依赖项。

2.5.1. Connecting to Cassandra

您可以像注入任何其他Spring Bean一样注入自动配置的CassandraTemplate或CassandraCqlSession实例。spring.cassandra.*属性可用于自定义连接。通常,您需要提供keyspace-nameContact-Points以及本地数据中心名称,如下例所示:

Properties
Yaml
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1:9042,cassandrahost2:9042
spring.cassandra.local-datacenter=datacenter1
             
             

如果所有联系人的端口都相同,则可以使用快捷方式并仅指定主机名,如下例所示:

Properties
Yaml
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1
             
             
Those two examples are identical as the port default to 9042. If you need to configure the port, use spring.cassandra.port.

Cassandra驱动程序有自己的配置基础设施,可以加载类路径根目录下的Application.conf

默认情况下,Spring Boot不会查找这样的文件,但可以使用spring.cassandra.config加载一个文件。如果属性同时存在于spring.cassandra.*<和配置文件中,则spring.cassandra.*<中的值优先。

对于更高级的驱动程序定制,您可以注册任意数量的实现DriverConfigLoaderBuilderCustomizer.的BeanCqlSessionBuilderCustomizer类型的Bean可以自定义CqlSessionBuilderCustomizer

If you use CqlSessionBuilder to create multiple CqlSession beans, keep in mind the builder is mutable so make sure to inject a fresh copy for each session.

以下代码清单显示了如何注入Cassandra Bean:

Java
Kotlin
import org.springframework.data.cassandra.core.CassandraTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final CassandraTemplate template; public MyBean(CassandraTemplate template) { this.template = template; }  // ...  public long someMethod() { return this.template.count(User.class); } } 
             
             

如果添加您自己的CassandraTemplate类型的@Bean,它将替换缺省值。

2.5.2. Spring Data Cassandra Repositories

Spring Data包括对Cassandra的基本存储库支持。目前,这比前面讨论的JPA存储库有更多的限制,需要用@Query注释finder方法。

For complete details of Spring Data Cassandra, see the reference documentation.

2.6. Couchbase

Couchbase是一个开源、分布式、多模型的NoSQL面向文档的数据库,它针对交互式应用程序进行了优化。Spring Boot为Couchbase和由Spring data Couchbase提供的抽象提供了自动配置。有spring-boot-starter-data-couchbasespring-boot-starter-data-couchbase-reactive“启动者”可以方便地收集依赖项。

2.6.1. Connecting to Couchbase

您可以通过添加Couchbase SDK和一些配置来获得集群spring.Couchbase.*属性可用于自定义连接。通常,您需要提供连接字符串、用户名和密码,如下例所示:

Properties
Yaml
spring.couchbase.connection-string=couchbase://192.168.1.123
spring.couchbase.username=user
spring.couchbase.password=secret
             
             

还可以自定义某些ClusterEnvironment设置。例如,下面的配置更改了用于打开新的Bucket的超时时间,并启用了SSL支持:

Properties
Yaml
spring.couchbase.env.timeouts.connect=3s
spring.couchbase.env.ssl.key-store=/location/of/keystore.jks
spring.couchbase.env.ssl.key-store-password=secret
             
             
Check the spring.couchbase.env.* properties for more details. To take more control, one or more ClusterEnvironmentBuilderCustomizer beans can be used.

2.6.2. Spring Data Couchbase Repositories

Spring Data包括对Couchbase的存储库支持。有关Spring data Couchbase的完整详细信息,请参阅参考文档

您可以注入一个自动配置的Couchbase模板实例,就像注入任何其他SpringBean一样,前提是Couchbase ClientFactoryBean可用。如上所述,当集群可用,并且指定了存储桶名称时,就会出现这种情况:

Properties
Yaml
spring.data.couchbase.bucket-name=my-bucket
             
             

以下示例显示如何注入Couchbase模板Bean:

Java
Kotlin
import org.springframework.data.couchbase.core.CouchbaseTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final CouchbaseTemplate template; public MyBean(CouchbaseTemplate template) { this.template = template; }  // ...  public String someMethod() { return this.template.getBucketName(); } } 
             
             

您可以在自己的配置中定义几个Bean,以覆盖自动配置提供的Bean:

  • Couchbase MappingContext@Bean,名称为Couchbase MappingContext

  • CustomConversions@Bean,名称为Couchbase CustomConversions

  • Couchbase模板@Bean,名称为Couchbase模板

为了避免在您自己的配置中硬编码这些名称,您可以重用Spring data Couchbase提供的BeanNames。例如,您可以自定义要使用的转换器,如下所示:

Java
Kotlin
import org.assertj.core.util.Arrays; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.couchbase.config.BeanNames; import org.springframework.data.couchbase.core.convert.CouchbaseCustomConversions; @Configuration(proxyBeanMethods = false) public class MyCouchbaseConfiguration { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) public CouchbaseCustomConversions myCustomConversions() { return new CouchbaseCustomConversions(Arrays.asList(new MyConverter())); } } 
             
             

2.7. LDAP

LDAP(轻量级目录访问协议)是一种开放的、供应商中立的行业标准应用程序协议,用于通过IP网络访问和维护分布式目录信息服务。Spring Boot提供了对任何兼容的LDAP服务器的自动配置,以及对Unound ID的嵌入式内存中的LDAP服务器的支持。

Spring data LDAP提供了LDAP抽象。有一个SpringBoot-starter-data-ldap“starter”,用于以方便的方式收集依赖项。

2.7.1. Connecting to an LDAP Server

要连接到LDAP服务器,请确保声明对Spring-ot-starter-data-ldap“starter”或Spring-ldap-core的依赖关系,然后在您的应用程序中声明服务器的URL,如下例所示:

Properties
Yaml
spring.ldap.urls=ldap://myserver:1235
spring.ldap.username=admin
spring.ldap.password=secret
             
             

如果需要自定义连接设置,可以使用spring.ldap.basespring.ldap.base-Environment属性。

LdapConextSource是根据这些设置自动配置的。如果有可用的DirContextAuthenticationStrategyBean,则它与自动配置的LdapConextSource相关联。如果您需要对其进行自定义,例如使用PooledConextSource,您仍然可以注入自动配置的LdapContextSource。请确保将您的定制ContextSource标记为@Primary,以便自动配置的LdapTemplate使用它。

2.7.2. Spring Data LDAP Repositories

Spring Data包括对LDAP的存储库支持。有关Spring data LDAP的完整详细信息,请参阅参考文档

您还可以像插入任何其他Spring Bean一样注入自动配置的LdapTemplate实例,如下例所示:

Java
Kotlin
import java.util.List; import org.springframework.ldap.core.LdapTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final LdapTemplate template; public MyBean(LdapTemplate template) { this.template = template; }  // ...  public List<User> someMethod() { return this.template.findAll(User.class); } } 
             
             

2.7.3. Embedded In-memory LDAP Server

出于测试目的,Spring Boot支持在Unound ID中自动配置内存中的LDAP服务器。要配置服务器,请向com.unbounid:unboundo-ldapsdk添加依赖项,并声明一个spring.ldap.embedded.base-dn属性,如下所示:

Properties
Yaml
spring.ldap.embedded.base-dn=dc=spring,dc=io
             
             

可以定义多个基本DN值,但是,由于可分辨名称通常包含逗号,因此必须使用正确的表示法来定义它们。

在YAML文件中,您可以使用YAML列表表示法。在属性文件中,必须将索引作为属性名称的一部分包括在内:

Properties
Yaml
spring.ldap.embedded.base-dn[0]=dc=spring,dc=io
spring.ldap.embedded.base-dn[1]=dc=pivotal,dc=io
                  
                  

默认情况下,服务器在随机端口上启动并触发常规的LDAP支持。不需要指定spring.ldap.urls属性。

如果您的类路径上有一个schema.ldif文件,则使用它来初始化服务器。如果希望从不同的资源加载初始化脚本,还可以使用spring.ldap.embedded.ldif属性。

默认情况下,使用标准架构来验证LDIF文件。通过设置spring.ldap.embedded.validation.enabled属性,可以完全关闭验证。如果具有自定义属性,则可以使用spring.ldap.embedded.validation.schema定义自定义属性类型或对象类。

2.8. InfluxDB

InfluxDB是一个开源的时间序列数据库,针对运营监控、应用程序指标、物联网传感器数据和实时分析等领域的时间序列数据的快速、高可用性存储和检索进行了优化。

2.8.1. Connecting to InfluxDB

Spring Boot会自动配置InfluxDB实例,前提是impxdb-Java客户端在类路径上,并且设置了数据库的URL,如下例所示:

Properties
Yaml
spring.influx.url=https://172.0.0.1:8086
             
             

如果到InfluxDB的连接需要用户和密码,您可以相应地设置spring.impx.userspring.impx.password属性。

InfluxDB依赖于OkHttp。如果您需要在后台调优http客户端<代码>InfluxDB 的使用,您可以注册一个InfluxDbOkHttpClientBuilderProviderBean。

如果您需要对配置进行更多控制,请考虑注册一个InfluxDbCustomizerBean。

3. What to Read Next

您现在应该对如何将Spring Boot与各种数据技术结合使用有了一定的了解。从这里,您可以了解到Spring Boot对各种消息传递技术的支持,以及如何在您的应用程序中启用它们。