CDI Integration
仓库接口的实例通常由在使用 Spring 数据与 Spring 配合时最自然的容器创建。Spring 为创建 bean 实例提供了复杂的方法。Spring 数据 Redis 随附了一个定制的 CDI 扩展,该扩展在 CDI 环境中让你使用仓库抽象。此扩展是 JAR 的一部分,所以要激活它,可将 Spring 数据 Redis JAR 添加至你的类路径。
Instances of the repository interfaces are usually created by a container, for which Spring is the most natural choice when working with Spring Data. Spring offers sophisticated for creating bean instances. Spring Data Redis ships with a custom CDI extension that lets you use the repository abstraction in CDI environments. The extension is part of the JAR, so, to activate it, drop the Spring Data Redis JAR into your classpath.
然后,你可以通过对 RedisConnectionFactory
和 RedisOperations
实现一个 CDI Productor 并设置基础架构,如下图例所示:
You can then set up the infrastructure by implementing a CDI Producer for the RedisConnectionFactory
and RedisOperations
, as shown in the following example:
class RedisOperationsProducer {
@Produces
RedisConnectionFactory redisConnectionFactory() {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(new RedisStandaloneConfiguration());
connectionFactory.afterPropertiesSet();
connectionFactory.start();
return connectionFactory;
}
void disposeRedisConnectionFactory(@Disposes RedisConnectionFactory redisConnectionFactory) throws Exception {
if (redisConnectionFactory instanceof DisposableBean) {
((DisposableBean) redisConnectionFactory).destroy();
}
}
@Produces
@ApplicationScoped
RedisOperations<byte[], byte[]> redisOperationsProducer(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
template.setConnectionFactory(redisConnectionFactory);
template.afterPropertiesSet();
return template;
}
}
必要的设置会根据你的 JavaEE 环境而有所不同。
The necessary setup can vary, depending on your JavaEE environment.
Spring 数据 Redis CDI 扩展会将所有可用的仓库拾取为 CDI Bean,并在容器请求仓库类型 Bean 时为 Spring 数据仓库创建一个代理。因此,获取 Spring 数据仓库的实例问题就在于声明一个 @Injected
属性,如下图例所示:
The Spring Data Redis CDI extension picks up all available repositories as CDI beans and creates a proxy for a Spring Data repository whenever a bean of a repository type is requested by the container.
Thus, obtaining an instance of a Spring Data repository is a matter of declaring an @Injected
property, as shown in the following example:
class RepositoryClient {
@Inject
PersonRepository repository;
public void businessMethod() {
List<Person> people = repository.findAll();
}
}
Redis 仓库需要 RedisKeyValueAdapter
和 RedisKeyValueTemplate
实例。如果未找到提供的 Bean,Spring 数据 CDI 扩展会创建并管理这些 Bean。然而,你可以提供自己的 Bean 来配置 RedisKeyValueAdapter
和 RedisKeyValueTemplate
的特定属性。
A Redis Repository requires RedisKeyValueAdapter
and RedisKeyValueTemplate
instances.
These beans are created and managed by the Spring Data CDI extension if no provided beans are found.
You can, however, supply your own beans to configure the specific properties of RedisKeyValueAdapter
and RedisKeyValueTemplate
.