我使用 Spring boot 创建一个应用程序,我想查询文档并将其添加到 Solr。所以我为此使用Spring data solr,maven依赖是:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
然后我为 Solr 存储库配置创建一个配置类。感谢 Spring,一切都变得简单并且工作正常。
@Configuration
@EnableSolrRepositories(basePackages = { "xxx.xx.xx.resource.repository.solr" },multicoreSupport = true)
public class SolrConfiguration {
@Bean
public SolrClient solrClient(@Value("${solr.host}") String solrHost) {
return new HttpSolrClient(solrHost);
}
}
然后,我想添加一个自定义函数来保存文档,因为默认转换器无法转换我的嵌套 Java 对象。我打算使用 SolrClient
bean 或 SolrTemplate bean 进行保存。
public class HouseSolrRepositoryImpl extends SimpleSolrRepository<House, String> implements HouseSolrRepository{
@Autowired
private SolrClient solrClient;
@Override
public House save(House house) throw Exception{
// Do converting
solrClient.save(doc);
solrClient.commit();
return house;/
}
}
但是 Autowiring 的 SolrClient
的路径不会从文档对象的路径中获取 solrCoreName
(@Document(solrCoreName = "gettingstarted")
)。它只是请求 http://localhost:8983/solr
,而不是使用核心名称请求 http://localhost:8983/solr/gettingstarted
。
我猜 solrCoreName
将在初始化存储库 bean 期间设置,因此我的配置将不包含它。
另一方面,我发现 SimpleSolrRepository
的 SolrOperation
bean 也变为 null,并且所有其他查询(如 findOne()
)无法正常工作。
最佳答案
我似乎误解了 Spring Data 的一些概念,我们不应该将它与 native SolrOperations 一起使用。
我们可以简单地将 SolrJ 中的 SolrClient 与 Spring Data 一起使用。这是我的简单解决方案。
由于我在 Solr 中有多个核心,因此我为配置中的每个核心创建 SolrClient
(替换旧版本中的 SolrServer)。
@Bean
public SolrClient gettingStartedSolrClient(@Value("${solr.host}") String solrHost){
return new ConcurrentUpdateSolrClient(solrHost+"/gettingstarted");
}
@Bean
public SolrClient anotherSolrClient(@Value("${solr.host}") String solrHost){
return new ConcurrentUpdateSolrClient(solrHost+"/anotherCore");
}
然后我们可以通过 Autowiring SolrClient
bean 在 Solr dao 类中使用它。
关于java - 如何在实现自定义 Spring 数据 solr 存储库时注入(inject) SolrOperations bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588412/