Spring Framework 为使用 SQL 数据库提供了广泛的支持,使用
Java 的
使用内存中的嵌入式数据库开发应用程序通常是方便的。显然,在内存数据库中不提供持久存储。当应用程序启动时,你需要填充数据库,并准备在应用程序结束时丢弃数据。
Spring Boot 可以自动配置嵌入式 H2、HSQL 和 Derby 数据库。你不需要提供任何连接URL。只需要对要使用的嵌入式数据库包含构建依赖项。
例如,典型的 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.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver
更多支持的选项请查阅 例如,如果使用 Tomcat 连接池,你可以自定义许多附加设置,如下面的示例所示: # Number of ms to wait before throwing an exception if no connection is available. spring.datasource.tomcat.max-wait=10000 # Maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active=50 # Validate the connection before borrowing it from the pool. spring.datasource.tomcat.test-on-borrow=true 如果将 Spring Boot 应用程序部署到应用服务器,你可能希望通过使用应用服务器的内置特性来配置和管理数据源,并通过使用 JNDI 访问它。
spring.datasource.jndi-name=java:jboss/datasources/customers
Spring 的 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final JdbcTemplate jdbcTemplate; @Autowired public MyBean(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } // ... }
你可以使用 spring.jdbc.template.max-rows=500
Java 持久化 API 是一种允许将对象映射到关系数据库的标准技术。
传统上,在
考虑使用 package com.example.myapp.domain; import java.io.Serializable; import javax.persistence.*; @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 shouldn't be used directly } public City(String name, String state) { this.name = name; this.country = country; } public String getName() { return this.name; } public String getState() { return this.state; } // ... etc }
Spring Data JPA 存储库是可以定义访问数据的接口。JPA 查询是从方法名称自动创建的。例如,
对于更复杂的查询,可以用 Spring Data 的
Spring Data 存储库通常从 下面的示例展示了一个典型的 Spring Data 存储库接口定义: package com.example.myapp.domain; import org.springframework.data.domain.*; import org.springframework.data.repository.*; public interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); }
默认情况下,只有使用嵌入式数据库(H2、HSQL 或 Derby)才能自动创建 JPA 数据库。可以通过使用 spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
前一个示例中的那行展示了将
默认情况下,DDL 执行(或验证)被推迟,直到
如果你正在运行一个 web 应用,Spring Boot 默认地注册 H2 数据库提供了一个基于浏览器的控制台,Spring Boot 会自动为你配置。当满足以下条件时,控制台自动配置:
Java 面向对象查询(jOOQ)是一种流行的产品,它从 Data Geekery 中生成Java代码,并通过它的 fluent API 来构建类型安全的 SQL 查询。商业版本和开源版本都可以与 Spring Boot 使用。
为了使用 jOOQ 类型安全查询,需要从数据库 schema 生成 Java 类。你可以按照 jOOQ 用户手册中的说明进行操作。如果你使用 <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>
jOOQ 提供的 fluent API 是通过 @Component public class JooqExample implements CommandLineRunner { private final DSLContext create; @Autowired public JooqExample(DSLContext dslContext) { this.create = 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); }
除非
更高级的定制可以通过定义自己的
如果你想完全控制 jOOQ 配置,则可以创建你自己的 Spring Data 提供了额外的项目来帮你访问各种各样的 NoSQL 技术,包含 MongoDB、Neo4J、Elasticsearch、Solr、Redis、Gemfire、Cassandra、Couchbase 和 LDAP。Spring Boot 为 Redis、MongoDB、Neo4j、Elasticsearch、Solr Cassandra、Couchbase 和 LDAP 提供了自动配置。你可以使用其它的项目,但你必须自己配置它们。在 projects.spring.io/spring-data 可以找到适当的参考文档。 Redis 是一个缓存、消息代理和功能丰富的键值存储。Spring Boot 使用 Spring Data Redis 为 Lettuce 和 Jedis 客户端库以及它们之上的抽象提供基础自动配置,
这有一个
你可以像你需要的其它任何 Spring bean 一样,注入一个自动配置 @Component public class MyBean { private StringRedisTemplate template; @Autowired public MyBean(StringRedisTemplate template) { this.template = template; } // ... }
如果你添加你自己的任意自动配置类型的
MongoDB 是一个开源的 NoSQL 文档数据库,它使用类似 JSON 的模式,而不是传统的基于表的关系数据。Spring Boot 为使用 MongoDB 提供了许多便利,包括
为了访问 Mongo 数据库,你可以注入一个自动配置的 import org.springframework.data.mongodb.MongoDbFactory; import com.mongodb.DB; @Component public class MyBean { private final MongoDbFactory mongo; @Autowired public MyBean(MongoDbFactory mongo) { this.mongo = mongo; } // ... public void example() { DB db = mongo.getDb(); // ... } }
你可以设置 spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test
或者,当你使用 Mongo 2.x,你可以指定 spring.data.mongodb.host=mongoserver spring.data.mongodb.port=27017
Spring Data MongoDB 提供了一个 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final MongoTemplate mongoTemplate; @Autowired public MyBean(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } // ... }
更完整的细节请参阅 Spring Data 包含 MongoDB 支持的库。与前面所讨论的 JPA 库,其基本原理是,查询的自动构建,以及基于名称的方法。
实际上,Spring Data JPA 和 Spring Data MongoDB 共享同样的公共基础内容。你可以拿来前面的 JPA 例子,假设 package com.example.myapp.domain; import org.springframework.data.domain.*; import org.springframework.data.repository.*; public interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); }
Spring Boot 为嵌入式 Mongo提供了自动配置。为了在你的 Spring Boot 应用程序中使用它,请添加一个
Mongo 监听的端口可以通过设置
如果在类路径上有 SLF4J,则由 Mongo 生成的输出自动路由到名为
你可以声明自己的
Neo4j 是一个开源的 NoSQL 图形数据库,为第一级关系的节点关系使用丰富的数据模型,这是比传统关系型数据库更适合连接大数据。Spring Boot 提供了几个使用 Neo4j 有用的工具,包括
你可以像其它你需要的 Spring Bean 那样,注入自动配置的 @Component public class MyBean { private final Neo4jTemplate neo4jTemplate; @Autowired public MyBean(Neo4jTemplate neo4jTemplate) { this.neo4jTemplate = neo4jTemplate; } // ... }
你可以通过添加
你可以通过设置 spring.data.neo4j.uri=http://my-server:7474 spring.data.neo4j.username=neo4j spring.data.neo4j.password=secret
如果你在应用程序中添加了 spring.data.neo4j.uri=file://var/tmp/graph.db
默认情况下,如果你正在运行一个 web 应用程序,会话会绑定到处理整个请求的线程上(即,它使用 "Open Session in View" 模式)。如果你不希望这种行为,添加以下行到你的 spring.data.neo4j.open-in-view=false
Spring Data 包含支持 Neo4j 的库。
事实上,Spring Data JPA 和 Spring Data Neo4j 共享同样的公共基础内容,你可以拿来前面的 JPA 例子,假设
若要启用库支持(并可选地支持 @EnableNeo4jRepositories(basePackages = "com.example.myapp.repository")
@EnableTransactionManagement
下面的示例展示一个 Neo4j 存储库的接口定义: package com.example.myapp.domain; import org.springframework.data.domain.*; import org.springframework.data.repository.*; public interface CityRepository extends GraphRepository<City> { Page<City> findAll(Pageable pageable); City findByNameAndCountry(String name, String country); }
Spring Data Gemfire 为访问 Pivotal Gemfire 数据管理平台提供了方便的 Spring 友好工具。这有一个
Apache Solr 是一个搜索引擎。Spring Boot 使用 Spring Data Solr 提供 Solr 5 客户端库和它之上的抽象提供基本自动配置。
你可以像任何其它 Spring bean 一样注入一个自动配置的 @Component public class MyBean { private SolrClient solr; @Autowired public MyBean(SolrClient solr) { this.solr = solr; } // ... }
如果你添加了你自己的 Spring Data 支持 Apache Solr 的存储库。与前面所讨论的 JPA 存储库一样,其基本原理是,基于你的方法名称自动构建查询。
事实上,Spring Data JPA 和 Spring Data Solr 共享同样的公共基础内容,你可以拿来前面的 JPA 例子,假设
Elasticsearch 是一个开源的,分布式的,RESTful 搜索和分析引擎。Spring Boot 为 Elasticsearch 提供基本自动配置。 Spring Boot 支持多种 HTTP 客户端:
传输客户端仍然是由 Spring Data Elasticsearch 使用,你可以使用 Elasticsearch 可以使用两个不同的 REST 客户端来查询集群:"Low Level" 客户端和 "High Level" 客户端。
如果你类路上有 spring.elasticsearch.rest.uris=http://search.example.com:9200 spring.elasticsearch.rest.username=user spring.elasticsearch.rest.password=secret
你还可以注册任意数量的 bean 来实现
如果你类路径上有
如果你的类路径上有 spring.elasticsearch.jest.uris=http://search.example.com:9200 spring.elasticsearch.jest.read-timeout=10000 spring.elasticsearch.jest.username=user spring.elasticsearch.jest.password=secret
你还可以注册任意数量的 bean,这些 bean 实现 static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer { @Override public void customize(HttpClientConfig.Builder builder) { builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5); } }
要完全控制注册,定义一个
为了连接到 Elasticsearch,你必须提供一个或多个集群节点的地址。可以通过设置 spring.data.elasticsearch.cluster-nodes=localhost:9300
@Component public class MyBean { private final ElasticsearchTemplate template; public MyBean(ElasticsearchTemplate template) { this.template = template; } // ... }
如果你添加了自己的 Spring Data 包括支持 Elasticsearch 的存储库。与前面所讨论的 JPA 存储库一样,其基本原理是,基于你的方法名称自动构建查询。
实际上,Spring Data JPA 和 Spring Data Elasticsearch 共享同样的公共基础内容,你可以拿来前面的 JPA 例子,假设
Cassandra 是一个开源的分布式数据库管理系统,用于处理大量商业服务器上的大数据。Spring Boot 使用 Spring Data Cassandra 为 Cassandra 以及之上的抽象提供了自动配置。有一个
你可以像其它 Spring bean 一样,注入一个自动配置的 spring.data.cassandra.keyspace-name=mykeyspace spring.data.cassandra.contact-points=cassandrahost1,cassandrahost2 下面的代码列表展示了如何注入一个 Cassandra bean: @Component public class MyBean { private CassandraTemplate template; @Autowired public MyBean(CassandraTemplate template) { this.template = template; } // ... }
如果你添加了自己的
Spring Data 包含支持 Cassandra 的存储库。目前来说,这比前面讨论的 JPA 存储库更有限,需要用
Couchbase 是一个开源的、分布式的、多模型 NoSql 面向文档数据库,它是交互应用的最优方案。Spring Boot 使用 Spring Data Couchbase 为 Couchbase 和之上的抽象提供了自动配置。
你可以通过添加 Couchbase SDK 和一些配置来获得一个 spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123 spring.couchbase.bucket.name=my-bucket spring.couchbase.bucket.password=secret
还可以自定义一些 spring.couchbase.env.timeouts.connect=3000 spring.couchbase.env.ssl.key-store=/location/of/keystore.jks spring.couchbase.env.ssl.key-store-password=secret
查看 Spring Data 包含支持 Couchbase 的库。有关 Spring Data Couchbase 的完整细节,请参阅参考文档。
你可以像其它任何 Spring bean 一样,注入一个自动配置的 下面的示例展示了如何注入一个 Couchbase bean: @Component public class MyBean { private final CouchbaseTemplate template; @Autowired public MyBean(CouchbaseTemplate template) { this.template = template; } // ... } 你可以在自己的配置中定义一些 bean 来覆盖自动配置所提供的那些 bean:
为了避免在自己的配置中对这些名称进行硬编码,可以重用 Spring Data Couchbase 提供的 @Configuration public class SomeConfiguration { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) public CustomConversions myCustomConversions() { return new CustomConversions(...); } // ... }
LDAP (Lightweight Directory Access Protocol)是一种开放的,供应商中立的,行业标准的应用协议,用于访问和维护 IP 网络上的分布式目录信息服务。Spring Boot 为任何兼容的 LDAP 服务器提供了自动配置,并从 UnboundID 支持嵌入式内存 LDAP 服务器。
LDAP 抽象由 Spring Data LDAP 提供。
若要连接到 LDAP 服务器,请确保在 spring.ldap.urls=ldap://myserver:1235 spring.ldap.username=admin spring.ldap.password=secret
如果需要自定义连接设置,你可以使用
基于这些设置自动配置一个 Spring Data 包含支持 LDAP 的存储库。有关 Spring Data LDAP 的完整细节,请参阅参考文档。
你也可以像其它任何 Spring bean 一样注入一个自动配置的 @Component public class MyBean { private final LdapTemplate template; @Autowired public MyBean(LdapTemplate template) { this.template = template; } // ... }
为了测试的目的,Spring Boot 支持 UnboundID 的内存 LDAP 服务器的自动配置。若要配置服务器,请添加依赖到 spring.ldap.embedded.base-dn=dc=spring,dc=io
默认情况下,服务器在随机端口启动,并触发常规 LDAP 支持。不需要指定
如果类路径上有一个
默认情况下,一个标准 scheam 用于验证 InfluxDB 是一个开源的时间序列数据库,用于在操作控制、应用度量、物联网传感器数据和实时分析等领域中对时间序列数据的快速、高可用性存储和检索进行优化。
Spring Boot 会自动配置一个 spring.influx.url=http://172.0.0.1:8086
如果连接到 InfluxDB 需要一个用户和密码,则可以相应的设置
InfluxDB 依赖于 OkHttp。如果需要调整 http 客户端
Spring Framework 为透明地向应用程序添加缓存提供了支持。在其核心上,抽象的将缓存应用于方法,从而基于缓存中可用的信息来减少执行次数。缓存逻辑被透明地应用,对调用者没有任何干扰。Spring Boot 自动配置缓存基础结构,只要通过
简而言之,向服务的操作中添加缓存与向其方法添加相关注解一样简单,如下面的示例所示: import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; @Component public class MathService { @Cacheable("piDecimals") public int computePiDecimal(int i) { // ... } }
这个示例展示了在潜在的高代价操作上使用缓存。在调用
如果你不添加任何特定的缓存库,Spring Boot 将自动配置在内存中使用并发映射的简单提供者。当需要缓存时(例如前面示例中的
缓存抽象不提供实际的存储,依赖于由
如果尚未定义
如果 @Bean public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() { return new CacheManagerCustomizer<ConcurrentMapCacheManager>() { @Override public void customize(ConcurrentMapCacheManager cacheManager) { cacheManager.setAllowNullValues(false); } }; }
如果上下文至少定义了一个
JCache 通过在类路上存在 可能出现不止一个提供者,在这种情况下,必须显式指定提供者。即使 JSR-107 标准不强制定义配置文件的位置的标准化方式,Spring Boot 尽其所能适应设置具有实现细节的缓存,如下面的示例所示: # Only necessary if more than one provider is present spring.cache.jcache.provider=com.acme.MyCachingProvider spring.cache.jcache.config=classpath:acme.xml
有两种方法来定制底层的
如果在类路径的根中找到一个名为 spring.cache.ehcache.config=classpath:config/another-config.xml
Spring Boot 对 Hazelcast 广泛的支持。如果 Infinispan 没有默认的配置文件位置,因此必须显式指定。否则,使用默认引导程序。 spring.cache.infinispan.config=infinispan.xml
可以通过设置
如果 Couchbase Java 客户端和 spring.cache.cache-names=cache1,cache2
然后,你可以定义一个 @Configuration public class CouchbaseCacheConfiguration { private final Cluster cluster; public CouchbaseCacheConfiguration(Cluster cluster) { this.cluster = cluster; } @Bean public Bucket anotherBucket() { return this.cluster.openBucket("another", "secret"); } @Bean public CacheManagerCustomizer<CouchbaseCacheManager> cacheManagerCustomizer() { return c -> { c.prepareCache("cache3", CacheBuilder.newInstance(anotherBucket()) .withExpiration(2)); }; } } 此示例配置重用通过自动配置创建的群集。
如果 Redis 是可用的和配置的,则自动配置 spring.cache.cache-names=cache1,cache2 spring.cache.redis.time-to-live=600000
Caffeine 是 Java 8 重写的 Guava 缓存,取代了对 Guava 的支持。如果 Caffeine 存在,
例如,以下配置创建 spring.cache.cache-names=cache1,cache2 spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
如果定义一个
如果找不到其它提供者,则配置使用 spring.cache.cache-names=cache1,cache2
如果这样做,并且应用程序使用未列出的缓存,那么在需要缓存时,它将在运行时失败,而不是在启动时。这与使用“未声明缓存”的“真正”缓存提供者的行为类似。 |