Spring Boot 与多种数据技术集成,包括 SQL 和 NoSQL。
1.SQL数据库
Spring框架为使用 SQL 数据库提供了广泛的支持,从直接 JDBC 访问JdbcTemplate到完整的“对象关系映射”技术(例如 Hibernate)。
Spring Data提供了额外级别的功能:Repository直接从接口创建实现并使用约定从方法名称生成查询。
1.1. 配置数据源
Java 的javax.sql.DataSource接口提供了使用数据库连接的标准方法。传统上,aDataSource使用 aURL以及一些凭据来建立数据库连接。
| 请参阅“操作方法”部分以获取更高级的示例,通常是为了完全控制数据源的配置。 | 
1.1.1. 嵌入式数据库支持
使用内存嵌入式数据库开发应用程序通常很方便。显然,内存数据库不提供持久存储。您需要在应用程序启动时填充数据库,并准备好在应用程序结束时丢弃数据。
| “操作方法”部分包括有关如何初始化数据库的部分。 | 
Spring Boot 可以自动配置嵌入式H2、HSQL和Derby数据库。您无需提供任何连接 URL。您只需包含对要使用的嵌入式数据库的构建依赖项。如果类路径上有多个嵌入式数据库,请设置spring.datasource.embedded-database-connection配置属性来控制使用哪一个。将属性设置为none禁用嵌入式数据库的自动配置。
| 如果您在测试中使用此功能,您可能会注意到,无论您使用的应用程序上下文数量如何,整个测试套件都会重复使用同一个数据库。如果您想确保每个上下文都有一个单独的嵌入式数据库,您应该设置 | 
例如,典型的 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>| 您需要依赖 spring-jdbc嵌入式数据库才能自动配置。在此示例中,它是通过 传递地拉入的spring-boot-starter-data-jpa。 | 
| 如果出于某种原因,您确实为嵌入式数据库配置了连接 URL,请注意确保禁用数据库的自动关闭功能。如果你使用H2,你应该 DB_CLOSE_ON_EXIT=FALSE这样做。如果您使用HSQLDB,您应该确保shutdown=true不使用它。禁用数据库的自动关闭可以让 Spring Boot 控制数据库何时关闭,从而确保在不再需要访问数据库时关闭数据库。 | 
1.1.3. 数据源配置
数据源配置由spring.datasource.*. 例如,您可以在 中声明以下部分application.properties:
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpassspring:
  datasource:
    url: "jdbc:mysql://localhost/test"
    username: "dbuser"
    password: "dbpass"| 您至少应该通过设置 spring.datasource.url属性来指定 URL。否则,Spring Boot 会尝试自动配置嵌入式数据库。 | 
| Spring Boot 可以从 URL 推断出大多数数据库的 JDBC 驱动程序类。如果需要指定特定的类,可以使用该 spring.datasource.driver-class-name属性。 | 
| 为了创建池 DataSource,我们需要能够验证有效的Driver类是否可用,因此我们在执行任何操作之前进行检查。换句话说,如果您设置了spring.datasource.driver-class-name=com.mysql.jdbc.Driver,那么该类必须是可加载的。 | 
请参阅DataSourceProperties参考资料 了解更多支持的选项。这些是无论实际实施如何都有效的标准选项。spring.datasource.hikari.*还可以通过使用各自的前缀( 、spring.datasource.tomcat.*、spring.datasource.dbcp2.*和)来微调特定于实现的设置spring.datasource.oracleucp.*。有关更多详细信息,请参阅您正在使用的连接池实现的文档。
例如,如果您使用Tomcat 连接池,则可以自定义许多其他设置,如以下示例所示:
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=truespring:
  datasource:
    tomcat:
      max-wait: 10000
      max-active: 50
      test-on-borrow: true如果没有可用连接,这会将池设置为在抛出异常之前等待 10000 毫秒,将最大连接数限制为 50,并在从池中借用连接之前验证连接。
1.1.4. 支持的连接池
Spring Boot 使用以下算法来选择特定的实现:
- 
我们更喜欢HikariCP的性能和并发性。如果 HikariCP 可用,我们总是选择它。 
- 
否则,如果 Tomcat 池 DataSource可用,我们就使用它。
- 
否则,如果Commons DBCP2可用,我们将使用它。 
- 
如果 HikariCP、Tomcat 和 DBCP2 都不可用,而 Oracle UCP 可用,则我们使用它。 
| 如果您使用 spring-boot-starter-jdbc或spring-boot-starter-data-jpa“starters”,您会自动获得对HikariCP. | 
您可以完全绕过该算法并通过设置属性来指定要使用的连接池spring.datasource.type。tomcat-jdbc如果您在默认提供的Tomcat 容器中运行应用程序,这一点尤其重要。
始终可以使用DataSourceBuilder. 如果您定义自己的DataSourcebean,则不会发生自动配置。支持以下连接池DataSourceBuilder:
- 
光CP 
- 
雄猫池化 Datasource
- 
共享 DBCP2 
- 
甲骨文 UCP 和 OracleDataSource
- 
Spring框架的 SimpleDriverDataSource
- 
氢2 JdbcDataSource
- 
PostgreSQL PGSimpleDataSource
- 
C3P0 
1.1.5。连接到 JNDI 数据源
如果将 Spring Boot 应用程序部署到应用程序服务器,您可能希望使用应用程序服务器的内置功能来配置和管理数据源,并使用 JNDI 访问它。
该属性可用作、和属性spring.datasource.jndi-name的替代,以从特定 JNDI 位置访问。例如,以下部分显示了如何访问定义的 JBoss AS :spring.datasource.urlspring.datasource.usernamespring.datasource.passwordDataSourceapplication.propertiesDataSource
spring.datasource.jndi-name=java:jboss/datasources/customersspring:
  datasource:
    jndi-name: "java:jboss/datasources/customers"1.2. 使用 JdbcTemplate
SpringJdbcTemplate和NamedParameterJdbcTemplate类是自动配置的,您可以将@Autowire它们直接添加到您自己的 bean 中,如以下示例所示:
@Component
public class MyBean {
    private final JdbcTemplate jdbcTemplate;
    public MyBean(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public void doSomething() {
        this.jdbcTemplate ...
    }
}
@Component
class MyBean(private val jdbcTemplate: JdbcTemplate) {
    fun doSomething() {
        jdbcTemplate.execute("delete from customer")
    }
}
您可以通过属性来自定义模板的一些属性spring.jdbc.template.*,如下例所示:
spring.jdbc.template.max-rows=500spring:
  jdbc:
    template:
      max-rows: 500| 在幕后
重用 NamedParameterJdbcTemplate相同的实例。如果定义了JdbcTemplate多个且不存在主要候选项,则不会自动配置。JdbcTemplateNamedParameterJdbcTemplate | 
1.3. JPA 和 Spring Data JPA
Java Persistence API 是一种标准技术,可让您将对象“映射”到关系数据库。POMspring-boot-starter-data-jpa提供了一种快速入门方法。它提供了以下关键依赖项:
- 
Hibernate:最流行的 JPA 实现之一。 
- 
Spring Data JPA:帮助您实现基于 JPA 的存储库。 
- 
Spring ORM:Spring 框架的核心 ORM 支持。 
| 我们在这里不过多讨论 JPA 或Spring Data的细节。您可以遵循spring.io中的“使用 JPA 访问数据”指南并阅读Spring Data JPA和Hibernate参考文档。 | 
1.3.1. 实体类
传统上,JPA“实体”类是在persistence.xml文件中指定的。对于 Spring Boot,这个文件不是必需的,而是使用“Entity Scanning”。默认情况下,将搜索主配置类(用@EnableAutoConfiguration或注释的那个)下面的所有包。@SpringBootApplication
任何用@Entity、@Embeddable、 或注解的类@MappedSuperclass都会被考虑。典型的实体类类似于以下示例:
@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
}
@Entity
class City : Serializable {
    @Id
    @GeneratedValue
    private val id: Long? = null
    @Column(nullable = false)
    var name: String? = null
        private set
    // ... etc
    @Column(nullable = false)
    var state: String? = null
        private set
    // ... additional members, often include @OneToMany mappings
    protected constructor() {
        // no-args constructor required by JPA spec
        // this one is protected since it should not be used directly
    }
    constructor(name: String?, state: String?) {
        this.name = name
        this.state = state
    }
}
| 您可以使用 @EntityScan注释自定义实体扫描位置。请参阅“ howto.html ”操作方法。 | 
1.3.2. Spring Data JPA 存储库
Spring Data JPA存储库是您可以定义来访问数据的接口。JPA 查询是根据您的方法名称自动创建的。例如,CityRepository接口可能声明一个findAllByState(String state)方法来查找给定州的所有城市。
对于更复杂的查询,您可以使用 Spring Data 的Query注释来注释您的方法。
Spring Data 存储库通常从Repository或CrudRepository接口扩展。@EnableAutoConfiguration如果您使用自动配置,将从包含主配置类(用或注释的那个@SpringBootApplication)的包中搜索存储库。
| 您可以使用 自定义位置来查找存储库 @EnableJpaRepositories。 | 
以下示例显示了典型的 Spring Data 存储库接口定义:
public interface CityRepository extends Repository<City, Long> {
    Page<City> findAll(Pageable pageable);
    City findByNameAndStateAllIgnoringCase(String name, String state);
}
interface CityRepository : Repository<City?, Long?> {
    fun findAll(pageable: Pageable?): Page<City?>?
    fun findByNameAndStateAllIgnoringCase(name: String?, state: String?): City?
}
Spring Data JPA 存储库支持三种不同的引导模式:默认、延迟和惰性。要启用延迟或延迟引导,请分别将该spring.data.jpa.repositories.bootstrap-mode属性设置为deferred或lazy。当使用延迟或惰性引导时,自动配置EntityManagerFactoryBuilder将使用上下文AsyncTaskExecutor(如果有)作为引导执行器。如果存在多个,applicationTaskExecutor则将使用指定的那个。
| 使用延迟或惰性引导时,请确保在应用程序上下文引导阶段之后延迟对 JPA 基础结构的任何访问。您可以使用它 | 
| 我们仅仅触及了 Spring Data JPA 的皮毛。有关完整的详细信息,请参阅Spring Data JPA 参考文档。 | 
1.3.3. Spring Data Envers 存储库
如果Spring Data Envers可用,JPA 存储库会自动配置为支持典型的 Envers 查询。
要使用 Spring Data Envers,请确保您的存储库扩展自RevisionRepository以下示例:
public interface CountryRepository extends RevisionRepository<Country, Long, Integer>, Repository<Country, Long> {
    Page<Country> findAll(Pageable pageable);
}
interface CountryRepository :
        RevisionRepository<Country?, Long?, Int>,
        Repository<Country?, Long?> {
    fun findAll(pageable: Pageable?): Page<Country?>?
}
| 有关更多详细信息,请查看Spring Data Envers 参考文档。 | 
1.3.4. 创建和删除 JPA 数据库
默认情况下,仅当您使用嵌入式数据库(H2、HSQL 或 Derby)时才会自动创建 JPA 数据库。您可以使用spring.jpa.*属性显式配置 JPA 设置。例如,要创建和删除表,您可以将以下行添加到您的application.properties:
spring.jpa.hibernate.ddl-auto=create-dropspring:
  jpa:
    hibernate.ddl-auto: "create-drop"| Hibernate 自己的内部属性名称(如果您记得更好的话)是 hibernate.hbm2ddl.auto。spring.jpa.properties.*您可以通过使用(在将它们添加到实体管理器之前删除前缀)来设置它以及其他 Hibernate 本机属性。以下行显示了为 Hibernate 设置 JPA 属性的示例: | 
spring.jpa.properties.hibernate[globally_quoted_identifiers]=truespring:
  jpa:
    properties:
      hibernate:
        "globally_quoted_identifiers": "true"前面示例中的行将属性的值传递true给hibernate.globally_quoted_identifiersHibernate 实体管理器。
默认情况下,DDL 执行(或验证)被推迟到开始为止ApplicationContext。还有一个spring.jpa.generate-ddl标志,但如果 Hibernate 自动配置处于活动状态,则不会使用它,因为设置ddl-auto更细粒度。
1.3.5。在视图中打开EntityManager
如果您正在运行 Web 应用程序,Spring Boot 默认情况下会注册OpenEntityManagerInViewInterceptor以应用“在视图中打开 EntityManager”模式,以允许在 Web 视图中延迟加载。如果您不希望出现这种行为,您应该spring.jpa.open-in-view在false您的application.properties.
1.4. Spring数据JDBC
Spring Data 包括对 JDBC 的存储库支持,并将自动为CrudRepository. 对于更高级的查询,@Query提供了注释。
当类路径上有必要的依赖项时,Spring Boot 将自动配置 Spring Data 的 JDBC 存储库。可以将它们添加到您的项目中,并仅依赖于spring-boot-starter-data-jdbc. 如有必要,您可以通过向应用程序添加@EnableJdbcRepositories注释或子类来控制 Spring Data JDBC 的配置。AbstractJdbcConfiguration
| 有关 Spring Data JDBC 的完整详细信息,请参阅参考文档。 | 
1.5. 使用 H2 的 Web 控制台
- 
您正在开发一个基于 servlet 的 Web 应用程序。 
- 
com.h2database:h2位于类路径上。
- 
您正在使用Spring Boot 的开发者工具。 
| 如果您不使用 Spring Boot 的开发人员工具,但仍想使用 H2 的控制台,则可以将该 spring.h2.console.enabled属性配置为 值true。 | 
| H2 控制台仅供开发期间使用,因此您应注意确保在生产中 spring.h2.console.enabled未将其设置为true。 | 
1.5.2. 在安全应用程序中访问 H2 控制台
H2 Console 使用框架,仅用于开发,没有实施 CSRF 保护措施。如果您的应用程序使用 Spring Security,则需要将其配置为
- 
对针对控制台的请求禁用 CSRF 保护, 
- 
将标头设置 X-Frame-Options为SAMEORIGIN来自控制台的响应。
有关CSRF和标头X-Frame-Options 的更多信息可以在 Spring Security 参考指南中找到。
在简单的设置中,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((frame) -> frame.sameOrigin()));
        return http.build();
    }
}
@Profile("dev")
@Configuration(proxyBeanMethods = false)
class DevProfileSecurityConfiguration {
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    fun h2ConsoleSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
        return http.authorizeHttpRequests(yourCustomAuthorization())
            .csrf { csrf -> csrf.disable() }
            .headers { headers -> headers.frameOptions { frameOptions -> frameOptions.sameOrigin() } }
            .build()
    }
}
| H2 控制台仅供开发期间使用。在生产中,禁用 CSRF 保护或允许网站使用框架可能会带来严重的安全风险。 | 
| PathRequest.toH2Console()当控制台的路径已自定义时,也会返回正确的请求匹配器。 | 
1.6. 使用 jOOQ
jOOQ 面向对象查询 ( jOOQ ) 是Data Geekery的一款流行产品,它从数据库生成 Java 代码,并允许您通过其流畅的 API 构建类型安全的 SQL 查询。商业版和开源版都可以与 Spring Boot 一起使用。
1.6.1. 代码生成
为了使用 jOOQ 类型安全查询,您需要从数据库模式生成 Java 类。您可以按照jOOQ 用户手册中的说明进行操作。如果您使用该jooq-codegen-maven插件并且还使用spring-boot-starter-parent“父 POM”,则可以安全地省略该插件的<version>标签。您还可以使用 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. 使用 DSLContext
jOOQ提供的Fluent API是通过org.jooq.DSLContext接口发起的。Spring Boot 自动将 a 配置DSLContext为 Spring Bean 并将其连接到您的应用程序DataSource。要使用DSLContext,您可以注入它,如以下示例所示:
@Component
public class MyBean {
    private final DSLContext create;
    public MyBean(DSLContext dslContext) {
        this.create = dslContext;
    }
}
@Component
class MyBean(private val create: DSLContext) {
}
| jOOQ 手册倾向于使用名为的变量 create来保存DSLContext. | 
然后,您可以使用DSLContext来构建查询,如以下示例所示:
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);
fun authorsBornAfter1980(): List<GregorianCalendar> {
    return create.selectFrom<Tables.TAuthorRecord>(Tables.AUTHOR)
        .where(Tables.AUTHOR?.DATE_OF_BIRTH?.greaterThan(GregorianCalendar(1980, 0, 1)))
        .fetch(Tables.AUTHOR?.DATE_OF_BIRTH)
}
1.7. 使用 R2DBC
反应式关系数据库连接 ( R2DBC ) 项目为关系数据库带来了反应式编程 API。R2DBCio.r2dbc.spi.Connection提供了一种使用非阻塞数据库连接的标准方法。连接是通过使用 a 提供的ConnectionFactory,类似于DataSourcejdbc 中的 a。
ConnectionFactory配置由 中的外部配置属性控制spring.r2dbc.*。例如,您可以在 中声明以下部分application.properties:
spring.r2dbc.url=r2dbc:postgresql://localhost/test
spring.r2dbc.username=dbuser
spring.r2dbc.password=dbpassspring:
  r2dbc:
    url: "r2dbc:postgresql://localhost/test"
    username: "dbuser"
    password: "dbpass"| 您不需要指定驱动程序类名,因为 Spring Boot 从 R2DBC 的连接工厂发现中获取驱动程序。 | 
| 至少应该提供网址。URL 中指定的信息优先于各个属性,即 name、username和password池选项。 | 
| “操作方法”部分包括有关如何初始化数据库的部分。 | 
要自定义由 所创建的连接ConnectionFactory,即设置您不想(或无法)在中央数据库配置中配置的特定参数,您可以使用ConnectionFactoryOptionsBuilderCustomizer @Bean. 以下示例显示如何手动覆盖数据库端口,而其余选项则取自应用程序配置:
@Configuration(proxyBeanMethods = false)
public class MyR2dbcConfiguration {
    @Bean
    public ConnectionFactoryOptionsBuilderCustomizer connectionFactoryPortCustomizer() {
        return (builder) -> builder.option(ConnectionFactoryOptions.PORT, 5432);
    }
}
@Configuration(proxyBeanMethods = false)
class MyR2dbcConfiguration {
    @Bean
    fun connectionFactoryPortCustomizer(): ConnectionFactoryOptionsBuilderCustomizer {
        return ConnectionFactoryOptionsBuilderCustomizer { builder ->
            builder.option(ConnectionFactoryOptions.PORT, 5432)
        }
    }
}
以下示例显示如何设置一些 PostgreSQL 连接选项:
@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);
    }
}
@Configuration(proxyBeanMethods = false)
class MyPostgresR2dbcConfiguration {
    @Bean
    fun postgresCustomizer(): ConnectionFactoryOptionsBuilderCustomizer {
        val options: MutableMap<String, String> = HashMap()
        options["lock_timeout"] = "30s"
        options["statement_timeout"] = "60s"
        return ConnectionFactoryOptionsBuilderCustomizer { builder ->
            builder.option(PostgresqlConnectionFactoryProvider.OPTIONS, options)
        }
    }
}
当ConnectionFactorybean 可用时,常规 JDBCDataSource自动配置就会停止。如果您想保留 JDBCDataSource自动配置,并且愿意接受在反应式应用程序中使用阻塞 JDBC API 的风险,请在应用程序中添加@Import(DataSourceAutoConfiguration.class)一个@Configuration类以重新启用它。
1.7.1. 嵌入式数据库支持
与JDBC 支持类似,Spring Boot 可以自动配置嵌入式数据库以进行反应式使用。您无需提供任何连接 URL。您只需包含对要使用的嵌入式数据库的构建依赖项,如以下示例所示:
<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-h2</artifactId>
    <scope>runtime</scope>
</dependency>| 如果您在测试中使用此功能,您可能会注意到,无论您使用的应用程序上下文数量如何,整个测试套件都会重复使用同一个数据库。如果您想确保每个上下文都有一个单独的嵌入式数据库,您应该设置 | 
1.7.2. 使用数据库客户端
beanDatabaseClient是自动配置的,您可以将@Autowire其直接添加到您自己的 bean 中,如以下示例所示:
@Component
public class MyBean {
    private final DatabaseClient databaseClient;
    public MyBean(DatabaseClient databaseClient) {
        this.databaseClient = databaseClient;
    }
}
@Component
class MyBean(private val databaseClient: DatabaseClient) {
}
1.7.3。Spring Data R2DBC 存储库
Spring Data R2DBC存储库是您可以定义来访问数据的接口。查询是根据您的方法名称自动创建的。例如,CityRepository接口可能声明一个findAllByState(String state)方法来查找给定州的所有城市。
对于更复杂的查询,您可以使用 Spring Data 的Query注释来注释您的方法。
Spring Data 存储库通常从Repository或CrudRepository接口扩展。@EnableAutoConfiguration如果您使用自动配置,将从包含主配置类(用或注释的那个@SpringBootApplication)的包中搜索存储库。
以下示例显示了典型的 Spring Data 存储库接口定义:
public interface CityRepository extends Repository<City, Long> {
    Mono<City> findByNameAndStateAllIgnoringCase(String name, String state);
}
interface CityRepository : Repository<City?, Long?> {
    fun findByNameAndStateAllIgnoringCase(name: String?, state: String?): Mono<City?>?
}
| 我们仅仅触及了 Spring Data R2DBC 的皮毛。有关完整的详细信息,请参阅Spring Data R2DBC 参考文档。 | 
2. 使用 NoSQL 技术
Spring Data 提供了其他项目来帮助您访问各种 NoSQL 技术,包括:
其中,Spring Boot 为 Cassandra、Couchbase、Elasticsearch、LDAP、MongoDB、Neo4J 和 Redis 提供自动配置。此外,Spring Boot for Apache Geode为 Apache Geode提供自动配置。您可以使用其他项目,但必须自己配置它们。请参阅spring.io/projects/spring-data上的相应参考文档。
Spring Boot 还为 InfluxDB 客户端提供自动配置。
2.1. 雷迪斯
Redis是一个缓存、消息代理和功能丰富的键值存储。Spring Boot 为Lettuce和Jedis客户端库以及Spring Data Redis提供的抽象提供基本的自动配置。
有一个spring-boot-starter-data-redis“Starter”可以方便地收集依赖项。默认情况下,它使用Lettuce。该启动器可以处理传统应用程序和反应式应用程序。
| 我们还提供了一个 spring-boot-starter-data-redis-reactive“Starter”,以便与其他商店保持一致并提供反应性支持。 | 
2.1.1. 连接到 Redis
您可以像注入任何其他 Spring Bean 一样注入自动配置的RedisConnectionFactory、StringRedisTemplate或 vanilla实例。RedisTemplate以下清单显示了此类 bean 的示例:
@Component
public class MyBean {
    private final StringRedisTemplate template;
    public MyBean(StringRedisTemplate template) {
        this.template = template;
    }
}
@Component
class MyBean(private val template: StringRedisTemplate) {
}
默认情况下,实例尝试连接到位于 的 Redis 服务器localhost:6379。您可以使用spring.data.redis.*属性指定自定义连接详细信息,如以下示例所示:
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.database=0
spring.data.redis.username=user
spring.data.redis.password=secretspring:
  data:
    redis:
      host: "localhost"
      port: 6379
      database: 0
      username: "user"
      password: "secret"| 您还可以注册任意数量的 Bean 来实现 LettuceClientConfigurationBuilderCustomizer更高级的自定义。ClientResources也可以使用 进行定制ClientResourcesBuilderCustomizer。如果你使用Jedis,JedisClientConfigurationBuilderCustomizer也是可以的。RedisStandaloneConfiguration或者,您可以注册、RedisSentinelConfiguration、 或类型的 beanRedisClusterConfiguration以完全控制配置。 | 
如果您添加自己的@Bean任何自动配置类型,它将替换默认类型(除了 的情况RedisTemplate,当排除是基于 bean 名称redisTemplate而不是其类型时)。
默认情况下,如果池连接工厂commons-pool2位于类路径上,则会自动配置。
通过设置属性,可以将自动配置RedisConnectionFactory配置为使用 SSL 与服务器进行通信,如下例所示:
spring.data.redis.ssl.enabled=truespring:
  data:
    redis:
      ssl:
        enabled: true可以在SSL 捆绑包中配置自定义 SSL 信任材料并将其应用到RedisConnectionFactory以下示例中:
spring.data.redis.ssl.bundle=examplespring:
  data:
    redis:
      ssl:
        bundle: "example"2.2. MongoDB
MongoDB是一个开源 NoSQL 文档数据库,它使用类似 JSON 的模式而不是传统的基于表的关系数据。Spring Boot 为使用 MongoDB 提供了多种便利,包括“Starters”spring-boot-starter-data-mongodb和spring-boot-starter-data-mongodb-reactive“Starters”。
2.2.1. 连接到 MongoDB 数据库
要访问 MongoDB 数据库,您可以注入自动配置的org.springframework.data.mongodb.MongoDatabaseFactory. 默认情况下,实例尝试连接到位于 的 MongoDB 服务器mongodb://localhost/test。以下示例显示如何连接到 MongoDB 数据库:
@Component
public class MyBean {
    private final MongoDatabaseFactory mongo;
    public MyBean(MongoDatabaseFactory mongo) {
        this.mongo = mongo;
    }
}
@Component
class MyBean(private val mongo: MongoDatabaseFactory) {
}
如果您定义了自己的MongoClient,它将用于自动配置合适的MongoDatabaseFactory.
自动配置MongoClient是使用MongoClientSettingsbean 创建的。如果您定义了自己的MongoClientSettings,它将不加修改地使用,并且spring.data.mongodb属性将被忽略。否则 aMongoClientSettings将被自动配置并应用属性spring.data.mongodb。无论哪种情况,您都可以声明一个或多个MongoClientSettingsBuilderCustomizerbean 来微调MongoClientSettings配置。每个将按照MongoClientSettings.Builder用于构建 的顺序被调用MongoClientSettings。
您可以设置该spring.data.mongodb.uri属性来更改 URL 并配置其他设置,例如副本集,如以下示例所示:
spring.data.mongodb.uri=mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/testspring:
  data:
    mongodb:
      uri: "mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/test"或者,您可以使用离散属性指定连接详细信息。例如,您可以在您的 中声明以下设置application.properties:
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=secretspring:
  data:
    mongodb:
      host: "mongoserver1.example.com"
      port: 27017
      additional-hosts:
      - "mongoserver2.example.com:23456"
      database: "test"
      username: "user"
      password: "secret"通过设置属性,可以将自动配置MongoClient配置为使用 SSL 与服务器进行通信,如下例所示:
spring.data.mongodb.uri=mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/test
spring.data.mongodb.ssl.enabled=truespring:
  data:
    mongodb:
      uri: "mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/test"
      ssl:
        enabled: true可以在SSL 捆绑包中配置自定义 SSL 信任材料并将其应用到MongoClient以下示例中:
spring.data.mongodb.uri=mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/test
spring.data.mongodb.ssl.bundle=examplespring:
  data:
    mongodb:
      uri: "mongodb://user:[email protected]:27017,mongoserver2.example.com:23456/test"
      ssl:
        bundle: "example"| 如果未指定,则使用 您还可以使用语法将端口指定为主机地址的一部分 | 
| 如果您不使用 Spring Data MongoDB,您可以注入一个 MongoClientbean 而不是使用MongoDatabaseFactory. 如果你想完全控制MongoDB连接的建立,你也可以声明你自己的MongoDatabaseFactorybeanMongoClient。 | 
| 如果您使用反应式驱动程序,则 SSL 需要 Netty。如果 Netty 可用并且要使用的工厂尚未自定义,则自动配置会自动配置该工厂。 | 
2.2.2. Mongo模板
Spring Data MongoDB提供了一个MongoTemplate设计与 Spring 的JdbcTemplate. 与 一样JdbcTemplate,Spring Boot 会自动配置一个 bean 供您注入模板,如下所示:
@Component
public class MyBean {
    private final MongoTemplate mongoTemplate;
    public MyBean(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
}
@Component
class MyBean(private val mongoTemplate: MongoTemplate) {
}
有关完整详细信息,请参阅MongoOperationsJavadoc。
2.2.3. Spring Data MongoDB 存储库
Spring Data 包括对 MongoDB 的存储库支持。与前面讨论的 JPA 存储库一样,基本原则是根据方法名称自动构造查询。
事实上,Spring Data JPA 和 Spring Data MongoDB 共享相同的公共基础设施。您可以采用前面的 JPA 示例,假设City现在是 MongoDB 数据类而不是 JPA @Entity,它以相同的方式工作,如以下示例所示:
public interface CityRepository extends Repository<City, Long> {
    Page<City> findAll(Pageable pageable);
    City findByNameAndStateAllIgnoringCase(String name, String state);
}
interface CityRepository :
    Repository<City?, Long?> {
    fun findAll(pageable: Pageable?): Page<City?>?
    fun findByNameAndStateAllIgnoringCase(name: String?, state: String?): City?
}
通过扫描找到存储库和文档。默认情况下,会搜索包含主配置类的包(用@EnableAutoConfiguration或注释的包)及其下面的所有包。您可以分别使用和自定义@SpringBootApplication查找存储库和文档的位置。@EnableMongoRepositories@EntityScan
| 有关 Spring Data MongoDB 的完整详细信息,包括其丰富的对象映射技术,请参阅其参考文档。 | 
2.3. 新4j
Neo4j是一个开源 NoSQL 图形数据库,它使用通过一流关系连接的丰富节点数据模型,比传统 RDBMS 方法更适合互联大数据。Spring Boot 为使用 Neo4j 提供了多种便利,包括spring-boot-starter-data-neo4j“Starter”。
2.3.1. 连接到 Neo4j 数据库
要访问 Neo4j 服务器,您可以注入自动配置的org.neo4j.driver.Driver. localhost:7687默认情况下,实例尝试使用 Bolt 协议连接到 Neo4j 服务器。以下示例展示了如何注入 Neo4j Driver,该 Neo4j 使您可以访问 a 等内容Session:
@Component
public class MyBean {
    private final Driver driver;
    public MyBean(Driver driver) {
        this.driver = driver;
    }
}
@Component
class MyBean(private val driver: Driver) {
}
您可以使用属性配置驱动程序的各个方面spring.neo4j.*。以下示例显示如何配置要使用的 uri 和凭据:
spring.neo4j.uri=bolt://my-server:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=secretspring:
  neo4j:
    uri: "bolt://my-server:7687"
    authentication:
      username: "neo4j"
      password: "secret"自动配置Driver是使用创建的ConfigBuilder。要微调其配置,请声明一个或多个ConfigBuilderCustomizerbean。每个将按照ConfigBuilder用于构建 的顺序被调用Driver。
2.3.2. Spring Data Neo4j 存储库
Spring Data 包括对 Neo4j 的存储库支持。有关 Spring Data Neo4j 的完整详细信息,请参阅参考文档。
与许多其他 Spring Data 模块一样,Spring Data Neo4j 与 Spring Data JPA 共享公共基础设施。您可以采用前面的 JPA 示例并将其定义City为 Spring Data Neo4j@Node而不是 JPA @Entity,并且存储库抽象以相同的方式工作,如以下示例所示:
public interface CityRepository extends Neo4jRepository<City, Long> {
    Optional<City> findOneByNameAndState(String name, String state);
}
interface CityRepository : Neo4jRepository<City?, Long?> {
    fun findOneByNameAndState(name: String?, state: String?): Optional<City?>?
}
“ Starter spring-boot-starter-data-neo4j”支持存储库支持以及事务管理。Neo4jTemplateSpring Boot 使用或beans支持经典和反应式 Neo4j 存储库ReactiveNeo4jTemplate。当 Project Reactor 在类路径上可用时,响应式样式也会自动配置。
通过扫描找到存储库和实体。默认情况下,会搜索包含主配置类的包(用@EnableAutoConfiguration或注释的包)及其下面的所有包。您可以分别使用和自定义@SpringBootApplication查找存储库和实体的位置。@EnableNeo4jRepositories@EntityScan
| 在使用反应式风格的应用程序中,a Java Kotlin  | 
2.4. 弹性搜索
Elasticsearch是一个开源、分布式、RESTful 搜索和分析引擎。Spring Boot 为 Elasticsearch 客户端提供基本的自动配置。
Spring Boot 支持多种客户端:
- 
官方低级 REST 客户端 
- 
官方 Java API 客户端 
- 
ReactiveElasticsearchClient由 Spring Data Elasticsearch提供
Spring Boot 提供了专用的“Starter” spring-boot-starter-data-elasticsearch,.
2.4.1. 使用 REST 客户端连接到 Elasticsearch
Elasticsearch 提供了两个不同的 REST 客户端,可用于查询集群:模块中的低级客户端org.elasticsearch.client:elasticsearch-rest-client和模块中的Java API 客户端co.elastic.clients:elasticsearch-java。此外,Spring Boot 还为模块中的响应式客户端提供支持org.springframework.data:spring-data-elasticsearch。默认情况下,客户端将定位localhost:9200. 您可以使用spring.elasticsearch.*属性来进一步调整客户端的配置方式,如以下示例所示:
spring.elasticsearch.uris=https://search.example.com:9200
spring.elasticsearch.socket-timeout=10s
spring.elasticsearch.username=user
spring.elasticsearch.password=secretspring:
  elasticsearch:
    uris: "https://search.example.com:9200"
    socket-timeout: "10s"
    username: "user"
    password: "secret"使用 RestClient 连接到 Elasticsearch
如果您elasticsearch-rest-client在类路径上,Spring Boot 将自动配置并注册一个RestClientbean。除了前面描述的属性之外,要进行微调,RestClient您还可以注册任意数量的 Bean 以实现RestClientBuilderCustomizer更高级的自定义。要完全控制客户端的配置,请定义一个RestClientBuilderbean。
此外,如果elasticsearch-rest-client-sniffer位于类路径上,aSniffer会自动配置为自动从正在运行的 Elasticsearch 集群中发现节点并将它们设置在RestClientbean 上。您可以进一步调整Sniffer配置方式,如以下示例所示:
spring.elasticsearch.restclient.sniffer.interval=10m
spring.elasticsearch.restclient.sniffer.delay-after-failure=30sspring:
  elasticsearch:
    restclient:
      sniffer:
        interval: "10m"
        delay-after-failure: "30s"使用 ElasticsearchClient 连接到 Elasticsearch
如果您co.elastic.clients:elasticsearch-java在类路径上,Spring Boot 将自动配置并注册一个ElasticsearchClientbean。
它ElasticsearchClient使用的传输取决于前面描述的RestClient。因此,前面描述的属性可用于配置ElasticsearchClient. 此外,您可以定义一个TransportOptionsbean 来进一步控制传输的行为。
使用 ReactiveElasticsearchClient 连接到 Elasticsearch
Spring Data Elasticsearch用于ReactiveElasticsearchClient以反应方式查询 Elasticsearch 实例。如果类路径上有 Spring Data Elasticsearch 和 Reactor,Spring Boot 将自动配置并注册一个ReactiveElasticsearchClient.
它ReactiveElasticsearchclient使用的传输取决于前面描述的RestClient。因此,前面描述的属性可用于配置ReactiveElasticsearchClient. 此外,您可以定义一个TransportOptionsbean 来进一步控制传输的行为。
2.4.2. 使用 Spring Data 连接到 Elasticsearch
ElasticsearchClient要连接到 Elasticsearch,必须定义一个bean,由 Spring Boot 自动配置或由应用程序手动提供(请参阅前面的部分)。完成此配置后,
ElasticsearchTemplate可以像任何其他 Spring bean 一样注入 an ,如以下示例所示:
@Component
public class MyBean {
    private final ElasticsearchTemplate template;
    public MyBean(ElasticsearchTemplate template) {
        this.template = template;
    }
}
@Component
class MyBean(private val template: org.springframework.data.elasticsearch.client.erhlc.ElasticsearchRestTemplate ) {
}
spring-data-elasticsearch在存在Reactor的情况下,Spring Boot 还可以自动配置ReactiveElasticsearchClient和ReactiveElasticsearchTemplateas beans。它们是其他 REST 客户端的响应式等价物。
2.4.3. Spring Data Elasticsearch 存储库
Spring Data 包括对 Elasticsearch 的存储库支持。与前面讨论的 JPA 存储库一样,基本原则是根据方法名称自动为您构建查询。
事实上,Spring Data JPA 和 Spring Data Elasticsearch 共享相同的公共基础设施。您可以采用前面的 JPA 示例,假设City现在是 Elasticsearch@Document类而不是 JPA @Entity,它的工作方式相同。
通过扫描找到存储库和文档。默认情况下,会搜索包含主配置类的包(用@EnableAutoConfiguration或注释的包)及其下面的所有包。您可以分别使用和自定义@SpringBootApplication查找存储库和文档的位置。@EnableElasticsearchRepositories@EntityScan
| 有关 Spring Data Elasticsearch 的完整详细信息,请参阅参考文档。 | 
ElasticsearchRestTemplateSpring Boot 使用或beans支持经典和反应式 Elasticsearch 存储库ReactiveElasticsearchTemplate。如果存在所需的依赖项,这些 bean 很可能是由 Spring Boot 自动配置的。
如果您希望使用自己的模板来支持 Elasticsearch 存储库,则可以添加您自己的ElasticsearchRestTemplate或ElasticsearchOperations @Bean,只要其名称为"elasticsearchTemplate"。同样适用于ReactiveElasticsearchTemplate和ReactiveElasticsearchOperations以及 bean 名称"reactiveElasticsearchTemplate"。
您可以选择使用以下属性禁用存储库支持:
spring.data.elasticsearch.repositories.enabled=falsespring:
  data:
    elasticsearch:
      repositories:
        enabled: false2.5. 卡桑德拉
Cassandra是一种开源分布式数据库管理系统,旨在处理跨多个商用服务器的大量数据。Spring Boot 为 Cassandra 提供自动配置,并在其之上由Spring Data Cassandra提供抽象。有一个spring-boot-starter-data-cassandra“Starter”可以方便地收集依赖项。
2.5.1. 连接到卡桑德拉
您可以像注入任何其他 Spring Bean 一样注入自动配置的实例CassandraTemplate或 Cassandra实例。CqlSession这些spring.cassandra.*属性可用于自定义连接。通常,您需要提供keyspace-name本地contact-points数据中心名称,如以下示例所示:
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1:9042,cassandrahost2:9042
spring.cassandra.local-datacenter=datacenter1spring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1:9042,cassandrahost2:9042"
    local-datacenter: "datacenter1"如果所有接触点的端口都相同,您可以使用快捷方式并仅指定主机名,如下例所示:
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1spring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1,cassandrahost2"
    local-datacenter: "datacenter1"| 这两个示例与默认端口相同 9042。如果需要配置端口,请使用spring.cassandra.port。 | 
通过设置属性,可以将自动配置CqlSession配置为使用 SSL 与服务器进行通信,如下例所示:
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1
spring.cassandra.ssl.enabled=truespring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1,cassandrahost2"
    local-datacenter: "datacenter1"
    ssl:
      enabled: true可以在SSL 捆绑包中配置自定义 SSL 信任材料并将其应用到CqlSession以下示例中:
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1
spring.cassandra.ssl.bundle=examplespring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1,cassandrahost2"
    local-datacenter: "datacenter1"
    ssl:
      bundle: "example"| Cassandra 驱动程序有自己的配置基础结构,可 Spring Boot 默认情况下不会查找此类文件,但可以使用 对于更高级的驱动程序自定义,您可以注册任意数量的实现 | 
| 如果您用来 CqlSessionBuilder创建多个CqlSessionbean,请记住构建器是可变的,因此请确保为每个会话注入一个新的副本。 | 
以下代码清单显示了如何注入 Cassandra bean:
@Component
public class MyBean {
    private final CassandraTemplate template;
    public MyBean(CassandraTemplate template) {
        this.template = template;
    }
}
@Component
class MyBean(private val template: CassandraTemplate) {
}
如果您添加自己的@Beanof type CassandraTemplate,它将替换默认值。
2.5.2. Spring Data Cassandra 存储库
Spring Data 包括对 Cassandra 的基本存储库支持。目前,这比前面讨论的 JPA 存储库更加有限,并且需要@Query带注释的查找器方法。
通过扫描找到存储库和实体。默认情况下,会搜索包含主配置类的包(用@EnableAutoConfiguration或注释的包)及其下面的所有包。您可以分别使用和自定义@SpringBootApplication查找存储库和实体的位置。@EnableCassandraRepositories@EntityScan
| 有关 Spring Data Cassandra 的完整详细信息,请参阅参考文档。 | 
2.6。沙发底座
Couchbase是一个开源、分布式、多模型、面向文档的 NoSQL 数据库,针对交互式应用程序进行了优化。Spring Boot 为 Couchbase 提供自动配置,并在其之上由Spring Data Couchbase提供抽象。有“ spring-boot-starter-data-couchbaseStarters spring-boot-starter-data-couchbase-reactive”可以方便地收集依赖项。
2.6.1. 连接到 Couchbase
Cluster您可以通过添加 Couchbase SDK 和一些配置来获得。这些spring.couchbase.*属性可用于自定义连接。通常,您需要提供连接字符串、用户名和密码,如以下示例所示:
spring.couchbase.connection-string=couchbase://192.168.1.123
spring.couchbase.username=user
spring.couchbase.password=secretspring:
  couchbase:
    connection-string: "couchbase://192.168.1.123"
    username: "user"
    password: "secret"还可以自定义一些设置ClusterEnvironment。例如,以下配置更改打开新文件的超时Bucket并通过引用已配置的SSL 捆绑包启用 SSL 支持:
spring.couchbase.env.timeouts.connect=3s
spring.couchbase.env.ssl.bundle=examplespring:
  couchbase:
    env:
      timeouts:
        connect: "3s"
      ssl:
        bundle: "example"| 检查 spring.couchbase.env.*属性以获取更多详细信息。为了更好地控制,ClusterEnvironmentBuilderCustomizer可以使用一种或多种豆子。 | 
2.6.2. Spring Data Couchbase 存储库
Spring Data 包括对 Couchbase 的存储库支持。
通过扫描找到存储库和文档。默认情况下,会搜索包含主配置类的包(用@EnableAutoConfiguration或注释的包)及其下面的所有包。您可以分别使用和自定义@SpringBootApplication查找存储库和文档的位置。@EnableCouchbaseRepositories@EntityScan
有关 Spring Data Couchbase 的完整详细信息,请参阅参考文档。
CouchbaseTemplate您可以像注入任何其他 Spring Bean 一样注入自动配置的实例,前提CouchbaseClientFactory是有可用的 Bean。当 aCluster可用时(如上所述)并且已指定存储桶名称,就会发生这种情况:
spring.data.couchbase.bucket-name=my-bucketspring:
  data:
    couchbase:
      bucket-name: "my-bucket"以下示例展示了如何注入CouchbaseTemplateBean:
@Component
public class MyBean {
    private final CouchbaseTemplate template;
    public MyBean(CouchbaseTemplate template) {
        this.template = template;
    }
}
@Component
class MyBean(private val template: CouchbaseTemplate) {
}
您可以在自己的配置中定义一些 bean,以覆盖自动配置提供的那些 bean:
- 
A 的 CouchbaseMappingContext@Bean名字为couchbaseMappingContext.
- 
A 的 CustomConversions@Bean名字为couchbaseCustomConversions.
- 
A 的 CouchbaseTemplate@Bean名字为couchbaseTemplate.
为了避免在您自己的配置中硬编码这些名称,您可以重用BeanNamesSpring Data Couchbase 提供的名称。例如,您可以自定义要使用的转换器,如下所示:
@Configuration(proxyBeanMethods = false)
public class MyCouchbaseConfiguration {
    @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
    public CouchbaseCustomConversions myCustomConversions() {
        return new CouchbaseCustomConversions(Arrays.asList(new MyConverter()));
    }
}
@Configuration(proxyBeanMethods = false)
class MyCouchbaseConfiguration {
    @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
    fun myCustomConversions(): CouchbaseCustomConversions {
        return CouchbaseCustomConversions(Arrays.asList(MyConverter()))
    }
}
2.7. LDAP
LDAP(轻量级目录访问协议)是一种开放的、供应商中立的行业标准应用协议,用于通过 IP 网络访问和维护分布式目录信息服务。Spring Boot 为任何兼容的 LDAP 服务器提供自动配置,并支持来自UnboundID 的嵌入式内存 LDAP 服务器。
LDAP 抽象由Spring Data LDAP提供。有一个spring-boot-starter-data-ldap“Starter”可以方便地收集依赖项。
2.7.1. 连接到 LDAP 服务器
要连接到 LDAP 服务器,请确保声明对spring-boot-starter-data-ldap“Starter”的依赖项,或者spring-ldap-core然后在 application.properties 中声明服务器的 URL,如以下示例所示:
spring.ldap.urls=ldap://myserver:1235
spring.ldap.username=admin
spring.ldap.password=secretspring:
  ldap:
    urls: "ldap://myserver:1235"
    username: "admin"
    password: "secret"如果需要自定义连接设置,可以使用spring.ldap.base和spring.ldap.base-environment属性。
AnLdapContextSource是根据这些设置自动配置的。如果DirContextAuthenticationStrategybean 可用,它将与自动配置的LdapContextSource. 如果您需要自定义它,例如使用 a PooledContextSource,您仍然可以注入自动配置的LdapContextSource. 确保将您的自定义标记ContextSource为,@Primary以便自动配置LdapTemplate使用它。
2.7.2. Spring Data LDAP 存储库
Spring Data 包括对 LDAP 的存储库支持。
通过扫描找到存储库和文档。默认情况下,会搜索包含主配置类的包(用@EnableAutoConfiguration或注释的包)及其下面的所有包。您可以分别使用和自定义@SpringBootApplication查找存储库和文档的位置。@EnableLdapRepositories@EntityScan
有关 Spring Data LDAP 的完整详细信息,请参阅参考文档。
LdapTemplate您还可以像注入任何其他 Spring Bean 一样注入自动配置的实例,如以下示例所示:
@Component
public class MyBean {
    private final LdapTemplate template;
    public MyBean(LdapTemplate template) {
        this.template = template;
    }
}
@Component
class MyBean(private val template: LdapTemplate) {
}
2.7.3. 嵌入式内存 LDAP 服务器
出于测试目的,Spring Boot 支持从UnboundID自动配置内存中 LDAP 服务器。要配置服务器,请添加依赖项com.unboundid:unboundid-ldapsdk并声明spring.ldap.embedded.base-dn属性,如下所示:
spring.ldap.embedded.base-dn=dc=spring,dc=iospring:
  ldap:
    embedded:
      base-dn: "dc=spring,dc=io"| 可以定义多个基本 dn 值,但是,由于可分辨名称通常包含逗号,因此必须使用正确的符号来定义它们。 在 yaml 文件中,您可以使用 yaml 列表表示法。在属性文件中,您必须包含索引作为属性名称的一部分: Properties Yaml  | 
默认情况下,服务器在随机端口上启动并触发常规 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. 连接到 InfluxDB
Spring Boot 会自动配置一个InfluxDB实例,前提是influxdb-java客户端位于类路径上并且设置了数据库的 URL,如下例所示:
spring.influx.url=https://172.0.0.1:8086spring:
  influx:
    url: "https://172.0.0.1:8086"如果连接到 InfluxDB 需要用户名和密码,您可以相应地设置spring.influx.user和spring.influx.password属性。
InfluxDB 依赖于 OkHttp。如果您需要调整 http 客户端InfluxDB在幕后使用,您可以注册一个InfluxDbOkHttpClientBuilderProviderbean。
如果您需要对配置进行更多控制,请考虑注册InfluxDbCustomizerbean。
3. 接下来读什么
您现在应该了解如何将 Spring Boot 与各种数据技术结合使用。从这里,您可以了解 Spring Boot 对各种消息传递技术的支持以及如何在应用程序中启用它们。