【问题标题】:Autowiring: expected at least 1 bean which qualifies as autowire candidate自动装配:预计至少有 1 个符合自动装配候选资格的 bean
【发布时间】:2020-02-12 15:29:41
【问题描述】:

我在 5 个重复的问题中尝试了大约 50 个潜在的解决方案,但没有任何效果。我正在尝试做的事情应该非常简单。只是尝试测试一个类....

主要建议似乎是用Component 正确注释,我已经尝试了很多版本。

我怀疑这可能与无法“找到”课程的测试有关,因为它们位于项目的不同部分,尽管我尝试输入 ComponentScan 并且没有成功。我相信这个项目结构是传统的:

src:
  main:
    java:
      com.projectname.location.api.services:
        LocationService
        LocationServiceImpl
  test:
    java:
      com.projectname.location.api.services:
        LocationServiceTest

界面:

package com.projectname.location.api.services;

public interface LocationRepository {

    /**
     * Read a CSV file to get IP addresses and locations.
     */

    void readCSV();

}

实现:

package com.projectname.location.api.services;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

@Component("locationRepository")
public class LocationRepositoryImpl implements LocationRepository {

    @Override
    public void readCSV() {
        String csvFile = "path_to_csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";

        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine())) {

                // use comma as separator
                String[] country = line.split(cvsSplitBy);

                System.out.println(country);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

还有测试:

package com.projectname.location.api.services;

import com.projectname.location.api.services.LocationRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Lazy;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ComponentScan("com.projectname.location.api")
public class LocationRepositoryTest {

    @Autowired
    @Qualifier("locationRepository")
    private LocationRepository locationRepository;

    @Test
    public void testReadCSV() {
        System.out.println("wow");
        locationRepository.readCSV();
    }

}

堆栈跟踪:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.projectname.location.api.services.LocationRepositoryTest': Unsatisfied dependency expressed through field 'locationRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.projectname.location.api.services.LocationRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value="locationRepository")}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.projectname.location.api.services.LocationRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value="locationRepository")}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
    ... 27 common frames omitted

【问题讨论】:

  • 能否添加异常堆栈跟踪?
  • 如何删除 RunWith 注释,删除 ComponentScan,删除 Autowired,并使用 new LocationRepositoryImpl() 自己创建类实例?您不需要 Spring 创建一个类的实例来对其进行单元测试。
  • 你能用@ContextConfiguration(classes = LocationRepository.class)代替@ComponentScan吗?
  • @Villat 我得到了同样的错误。
  • @JBNizet 有效,谢谢。不过,我可能需要将 Spring 合并到这个测试类中。

标签: java spring


【解决方案1】:

您需要使用@SpringBootTest 来加载要在测试中使用的应用程序上下文:

@RunWith(SpringRunner.class)
@SpringBootTest
public class LocationRepositoryTest {

    //Your tests

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 2017-10-24
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多