Spring @Inject无法正常工作

时间:2017-08-04 09:58:37

标签: java spring spring-data-jpa spring-data-elasticsearch

我最近将一个项目从Spring 4.3.1升级到4.3.4以及以前工作正常的项目,现在对我来说不起作用。

我使用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存储库重建它们,当我们注入repos时看起来像这样:

 @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()}

我在这里检查了几个问题,如 this this,快速浏览一下Spring文档,但找不到任何相关内容

我显然已经在不同的地方尝试了所有@Autowired@Component@Repository标记,没有正面结果

1 个答案:

答案 0 :(得分:2)

您需要使用@ContextConfiguration注释来注释您的测试类,该注释指向相关的@Configuration类,该类扫描并注册您尝试注入的所有这些bean。

请参阅@WebAppConfiguration的java文档:

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

  

请注意,@ WebAppConfiguration必须与@ContextConfiguration结合使用,可以在单个测试类中,也可以在测试类层次结构中使用。