2017-04-24 26 views
1

我使用Spring引導創建了一個應用程序,並且我想查詢並向Solr添加文檔。所以我使用Spring的數據解決方案爲此,maven依賴項是:如何在實現自定義Spring數據存儲庫時注入SolrOperations bean?

<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;/ 
    } 
} 

但自動裝配SolrClient的路徑不從文檔對象(@Document(solrCoreName = "gettingstarted"))的路徑得到solrCoreName。它只是要求http://localhost:8983/solr,而不是http://localhost:8983/solr/gettingstarted與核心名稱。

我猜solrCoreName將在初始化存儲庫bean時被設置,所以我的配置將不包含它。

另一方面,我發現SolrOperationSimpleSolrRepository也成爲空,並且所有其他查詢如findOne()無法正常工作。

回答

0

看來我誤解了Spring Data的一些概念,我們不應該將它與本機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"); 
} 

然後我們就可以通過自動裝配的SolrClient豆使用它在我們的Solr的DAO類。

+0

它適合你嗎?在我的情況下,每當我調用方法時,它都會不斷創建新的實例。 – Maralc

相關問題