CDI 集成
存储库接口的实例通常由容器创建,在使用 Spring Data 时,Spring 是最自然的选择。
Spring Data LDAP 包含一个自定义的 CDI 扩展,允许您在 CDI 环境中使用存储库抽象。
该扩展是 JAR 文件的一部分。
要激活它,只需将 Spring Data LDAP 的 JAR 文件放入您的类路径中。
现在,您可以通过实现一个用于 LdapTemplate 的 CDI Producer 来设置基础设施,如下例所示:
class LdapTemplateProducer {
@Produces
@ApplicationScoped
public LdapOperations createLdapTemplate() {
ContextSource contextSource = …
return new LdapTemplate(contextSource);
}
}
Spring Data LDAP 的 CDI 扩展会将 LdapTemplate 作为 CDI Bean 进行拾取,并在容器请求某个仓库类型的 Bean 时,为 Spring Data 仓库创建一个代理。
因此,获取 Spring Data 仓库的实例只需声明一个注入属性即可,如下例所示:
class RepositoryClient {
@Inject
PersonRepository repository;
public void businessMethod() {
List<Person> people = repository.findAll();
}
}