2017-08-04 76 views
1

我最近將一個項目從Spring 4.3.1升級到了4.3.4,以前用什麼工作都很好,現在只是不適合我。Spring @Inject不工作

我使用JPA,其中包含了一系列的倉庫類:

/** 
* Spring Data JPA repository for the DrugQualityCategory entity. 
*/ 

public interface DrugQualityCategoryRepository extends JpaRepository<DrugQualityCategory,Long> { 

    @Query(value = "Select a from DrugQualityCategory a where a.oldId = ?1") 
    DrugQualityCategory findOneByOldId(Integer oldId); 

} 

我們還使用ElasticSearch的搜索引擎,它創建這樣一個系列SearchRepositories的:

/** 
* Spring Data ElasticSearch repository for the Publication entity. 
*/ 
public interface DrugQualityCategorySearchRepository extends ElasticsearchRepository<Publication, Long> { 
} 

之一ES的問題在於它需要定期更新它的索引,所以爲此我們構建了一個測試,它將注入所有存儲庫並從JPA存儲庫重建它們,當我們注入回購時,看起來像這樣:

@RunWith(SpringJUnit4ClassRunner.class) 
    @WebAppConfiguration 
    @Transactional 
    @ActiveProfiles("syncElasticsearch") 
    public class SyncMysqlElasticSearch { 

    private Logger logger = LoggerFactory.getLogger(getClass()); 

    @Inject DrugQualityCategoryRepository drugQualityCategoryRepository; 
    @Inject TechniqueRepository techniqueRepository; 
    @Inject TradeDrugRepository tradeDrugRepository; 
    @Inject SurveyDataRepository surveyDataRepository; 
    @Inject RQAAQualityRepository rqaaQualityRepository; 

然後我們填補了ES實例:

drugQualityCategorySearchRepository.save(drugQualityCategoryRepository.findAll()); 
formulationSearchRepository.save(formulationRepository.findAll()); 
innDrugSearchRepository.save(innDrugRepository.findAll()); 
locationSearchRepository.save(locationRepository.findAll()); 
manufacturerSearchRepository.save(manufacturerRepository.findAll()); 

現在,我的問題是,當我嘗試啓動測試,我不斷獲取:

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name [class name] Unsatisfied dependency expressed 
through field [field name] nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [class name] available: expected at least 
1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()} 

我已檢查了幾個問題,如 thisthis,瀏覽了Spring文檔,但找不到任何相關內容

我明明嘗試了所有在不同的地方@Autowired@Component@Repository標籤,沒有陽性結果

+0

您如何設置測試環境? – Jan

+0

嗨,1月,我不知道我知道你在上下文中的含義,我有一個配置yml文件,它爲ES和JPA設置連接參數,除此之外,我只有代碼提取中的註釋在原來的問題 – Steven

回答

1

你需要用@ContextConfiguration註解指向它掃描和寄存器相關@Configuration類來註釋測試類所有這些你想要注入的豆子。

參見@WebAppConfiguration java的文檔:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html

注意@WebAppConfiguration必須與@ContextConfiguration一起使用,無論是在一個單一的測試類或測試類層次結構中。

+0

嗨,謝謝你的回覆,我一直在嘗試這個在最後一個小時,仍然無法使其工作。我試着只是添加上下文的註解,它不會把我的主類作爲參數,它說它不存在,它不會把類路徑*:作爲參數。 我已經嘗試將配置標記添加到主類,沒有運氣,也使得大多數組合與存儲庫標籤等...我錯過了什麼? – Steven

+1

@Steven你使用xml或Java conig或者spring啓動? – Plog

+0

使用Spring啓動的Java配置,我想我可能會做些什麼,我只是用ContextConfiguration註解(classes = DrugQualityDataManagerApp.class),現在它給了我我認爲是無關的錯誤 – Steven