CDI Integration
使用CDI(Contexts and Dependency Injection),可以简化Spring Data Elasticsearch存储库的设置。通过@Produces注解,可以在CDI容器中生成ElasticsearchTemplate实例。然后,CDI框架会自动将ElasticsearchOperations接口及其实现注入到客户端代码中,简化了存储库和Elasticsearch模板的访问。这种方法允许开发者专注于业务逻辑,而无需管理Elasticsearch连接。
Spring Data Elasticsearch 存储库也可以使用 CDI 功能设置。
The Spring Data Elasticsearch repositories can also be set up using CDI functionality.
Example 1. Spring Data Elasticsearch repositories using CDI
class ElasticsearchTemplateProducer {
@Produces
@ApplicationScoped
public ElasticsearchOperations createElasticsearchTemplate() {
// ... 1
}
}
class ProductService {
private ProductRepository repository; 2
public Page<Product> findAvailableBookByName(String name, Pageable pageable) {
return repository.findByAvailableTrueAndNameStartingWith(name, pageable);
}
@Inject
public void setRepository(ProductRepository repository) {
this.repository = repository;
}
}
1 | Create a component by using the same calls as are used in the Elasticsearch Operations chapter. |
2 | Let the CDI framework inject the Repository into your class. |