CDI Integration
仓库接口的实例通常由容器创建,其中最自然的选择是在使用 Spring Data 时使用 Spring。Spring 提供了 sofisticad的支持来创建 bean 实例,如此处 创建仓库实例 所述。从 1.1.0 版本开始,Spring Data JPA 提供了一个自定义 CDI 扩展,允许在 CDI 环境中使用仓库抽象。此扩展是 JAR 的一部分。要激活它,请在类路径中包括 Spring Data JPA 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 support for creating bean instances, as documented in Creating Repository Instances. As of version 1.1.0, Spring Data JPA ships with a custom CDI extension that allows using the repository abstraction in CDI environments. The extension is part of the JAR. To activate it, include the Spring Data JPA JAR on your classpath.
您可以通过实现 EntityManagerFactory
和 EntityManager
的 CDI 生产者来设置基础设施,如下例所示:
You can now set up the infrastructure by implementing a CDI Producer for the EntityManagerFactory
and EntityManager
, as shown in the following example:
class EntityManagerFactoryProducer {
@Produces
@ApplicationScoped
public EntityManagerFactory createEntityManagerFactory() {
return Persistence.createEntityManagerFactory("my-persistence-unit");
}
public void close(@Disposes EntityManagerFactory entityManagerFactory) {
entityManagerFactory.close();
}
@Produces
@RequestScoped
public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
public void close(@Disposes EntityManager entityManager) {
entityManager.close();
}
}
必需的设置可能因 JavaEE 环境而异。您可能只需要重新声明一个 EntityManager
为 CDI bean,如下所示:
The necessary setup can vary depending on the JavaEE environment. You may need to do nothing more than redeclare a EntityManager
as a CDI bean, as follows:
class CdiConfig {
@Produces
@RequestScoped
@PersistenceContext
public EntityManager entityManager;
}
在前面的示例中,容器必须能够自己创建 JPA EntityManager
。所有配置所做的就是将 JPA EntityManager
重新导出为 CDI bean。
In the preceding example, the container has to be capable of creating JPA EntityManagers
itself. All the configuration does is re-export the JPA EntityManager
as a CDI bean.
Spring 数据 JPA CDI 扩展将所有可用的 EntityManager
实例作为 CDI bean,并且在容器请求存储库类型的 bean 时为 Spring Data 存储库创建一个代理。因此,获取 Spring Data 存储库的实例只需要声明一个 @Injected
属性,如下例所示:
The Spring Data JPA CDI extension picks up all available EntityManager
instances 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();
}
}