没有可用的'mypackage.repository'类型的合格Bean:预计至少有1个有资格作为自动装配候选者的Bean

时间:2019-04-04 17:45:34

标签: spring-boot junit4

我在Junit4中有一个测试类,需要使用NutrientListService。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {

    private NutrientListService nutrientService;

    @Test
    public void someTest()
        Result re = Calculator.calculate(response, nutrientService)
}

我得到的营养服务为空,所以我尝试设置ApplicationContext。

@Configuration
@ComponentScan("myservice")
@ComponentScan("myrepository")
public class ApplicationContext {

    @Autowired
    NutrientListService nutrientService;
}

但是,我得到

Error creating bean with name 'nutrientListService': Unsatisfied dependency expressed through field 'nutrientListRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repositories.NutrientListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

这是服务:

@Service
@Component
public class NutrientListService {
    @Autowired
    private NutrientListRepository repo;
}

还有存储库:

@Repository
public interface NutrientListRepository extends MongoRepository<MyClass, String> {

    MyClass findByID(String ID);
}

有什么想法可以正确地连接服务吗?我需要通过它进行计算,因为它是参数之一。我是否必须使用应用程序上下文类或application-context.xml(找不到)?这样做最不为人知的方法是什么?我谢谢你。

1 个答案:

答案 0 :(得分:0)

@Configuration
@ComponentScan("myservice")
@ComponentScan("myrepository")
public class ApplicationContext {
    @Bean
    NutrientListService nutrientService(){
      new NutrientListService()
    }
}

然后使用@Autowired调用Bean

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {

    @Autowired
    NutrientListService nutrientService

    @Test
    public void someTest()
        Result re = Calculator.calculate(response, nutrientService)
}