CDI Integration
存储库接口的实例通常是由容器创建的,而使用 Spring Data 时,Spring 是最自然的选择。从 1.3.0 版开始,Spring Data MongoDB 附带一个自定义 CDI 扩展,让您可以在 CDI 环境中使用存储库抽象。此扩展是 JAR 的一部分。要激活它,请将 Spring Data MongoDB JAR 导入类路径。您现在可以通过为 MongoTemplate
实现一个 CDI 生成器来设置基础设施,如下例所示:
Instances of the repository interfaces are usually created by a container, and Spring is the most natural choice when working with Spring Data.
As of version 1.3.0, Spring Data MongoDB ships with a custom CDI extension that lets you use the repository abstraction in CDI environments.
The extension is part of the JAR.
To activate it, drop the Spring Data MongoDB JAR into your classpath.
You can now set up the infrastructure by implementing a CDI Producer for the MongoTemplate
, as the following example shows:
class MongoTemplateProducer {
@Produces
@ApplicationScoped
public MongoOperations createMongoTemplate() {
MongoDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(MongoClients.create(), "database");
return new MongoTemplate(factory);
}
}
Spring Data MongoDB CDI 扩展选取可用作 CDI Bean 的 MongoTemplate
,并在容器请求存储库类型的 Bean 时创建 Spring Data 存储库的代理。因此,获取 Spring Data 存储库的实例只是声明一个 @Inject
化属性的问题,如下例所示:
The Spring Data MongoDB CDI extension picks up the MongoTemplate
available as a CDI bean 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 @Inject
-ed property, as the following example shows:
class RepositoryClient {
@Inject
PersonRepository repository;
public void businessMethod() {
List<Person> people = repository.findAll();
}
}