我正在使用Spring-boot来实现Java应用程序。控制器之一称为HealthCheckerController,在application包中定义:

HealthCheckerController.java:

package application;

import healthchecker.Instance;
import healthchecker.InstanceRepository;

@RestController
public class HealthCheckerController {

    @Autowired
    private TopRepository topRepository;

    @Autowired
    private InstanceRepository instanceRepository;

    @SuppressWarnings("unused")
    private final static Logger logger = Logger.getLogger(HealthCheckerController.class);

    public HealthCheckerController(InstanceRepository instanceRepository) {
        this.instanceRepository = instanceRepository;
    }
   // other things not important here.
}


healthchecker包中,我定义了InstanceInstanceRepository

package healthchecker;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "instances", path = "instances")
public interface InstanceRepository extends MongoRepository<Instance, String> {

    Instance findByIpaddress(@Param("ipaddress") String ipaddress);

    List<Instance> findByAmi(String ami);
}


Instance模型:

package healthchecker;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

@Document(collection = "instances")
public class Instance {

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private String id;

    private String ipaddress;
    private String ami;
    // ..
}


现在,要测试控制器,我具有以下Unit Test

package application;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.google.gson.Gson;

/* Import local libraries */
import healthchecker.Instance;
import healthchecker.InstanceRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class HealthCheckerControllerTest {

    private MockMvc mvc;

    private final static Logger logger = Logger.getLogger(HealthCheckerControllerTest.class);

    @Autowired
    private InstanceRepository instanceRepository;

    private HttpMessageConverter<Object> mappingJackson2HttpMessageConverter;

    private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    @Autowired
    void setConverters(HttpMessageConverter<?>[] converters) {

        @SuppressWarnings("unchecked")
        HttpMessageConverter<Object> httpMessageConverter = (HttpMessageConverter<Object>) Arrays.asList(converters)
                .stream().filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get();
        this.mappingJackson2HttpMessageConverter = httpMessageConverter;

        Assert.assertNotNull("the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter);
    }

    @Before
    public void setUp() throws Exception {
        this.mvc = MockMvcBuilders.standaloneSetup(new HealthCheckerController(this.instanceRepository)).build();

        this.instanceRepository.deleteAll();
        Instance first = new Instance("10.20.30.40", "ami-xxxxxxxx");
        Instance second = new Instance("10.20.30.41", "ami-xxxxxxxx");
        this.instanceRepository.save(first);
        this.instanceRepository.save(second);

        for (Instance instance : this.instanceRepository.findAll()) {
            logger.info(instance);
        }
    }
   @Test
    public void testHealthChecker() throws Exception {
        this.mvc.perform(get("/healthchecker")).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].ipaddress", is("10.20.30.40")))
                .andExpect(jsonPath("$[0].ami", is("ami-xxxxxxxx")))
                .andExpect(jsonPath("$[1].ipaddress", is("10.20.30.41")))
                .andExpect(jsonPath("$[1].ami", is("ami-xxxxxxxx")));
    }
   // other things here
  }


我收到以下异常:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthCheckerController' defined in file [/Users/philippesouzamoraesribeiro/Documents/workspace/cloudos/target/classes/cloudos/HealthCheckerController.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [healthchecker.InstanceRepository] found for dependency [healthchecker.InstanceRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [healthchecker.InstanceRepository] found for dependency [healthchecker.InstanceRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthCheckerController' defined in file [/Users/philippesouzamoraesribeiro/Documents/workspace/cloudos/target/classes/cloudos/HealthCheckerController.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [healthchecker.InstanceRepository] found for dependency [healthchecker.InstanceRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [healthchecker.InstanceRepository] found for dependency [healthchecker.InstanceRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111) [spring-boot-test-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115) [junit-4.12.jar:4.12]
    at org.testng.junit.JUnit4TestRunner.start(JUnit4TestRunner.java:81) [testng-6.9.8.jar:?]
    at org.testng.junit.JUnit4TestRunner.run(JUnit4TestRunner.java:69) [testng-6.9.8.jar:?]
    at org.testng.TestRunner$1.run(TestRunner.java:689) [testng-6.9.8.jar:?]
    at org.testng.TestRunner.runWorkers(TestRunner.java:1014) [testng-6.9.8.jar:?]
    at org.testng.TestRunner.privateRunJUnit(TestRunner.java:720) [testng-6.9.8.jar:?]
    at org.testng.TestRunner.run(TestRunner.java:621) [testng-6.9.8.jar:?]
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359) [testng-6.9.8.jar:?]
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354) [testng-6.9.8.jar:?]
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312) [testng-6.9.8.jar:?]
    at org.testng.SuiteRunner.run(SuiteRunner.java:261) [testng-6.9.8.jar:?]
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) [testng-6.9.8.jar:?]
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) [testng-6.9.8.jar:?]
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1191) [testng-6.9.8.jar:?]
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1116) [testng-6.9.8.jar:?]
    at org.testng.TestNG.run(TestNG.java:1024) [testng-6.9.8.jar:?]
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:115) [surefire-testng-2.18.1.jar:2.18.1]
    at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:212) [surefire-testng-2.18.1.jar:2.18.1]
    at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:108) [surefire-testng-2.18.1.jar:2.18.1]
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:111) [surefire-testng-2.18.1.jar:2.18.1]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203) [surefire-booter-2.18.1.jar:2.18.1]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155) [surefire-booter-2.18.1.jar:2.18.1]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) [surefire-booter-2.18.1.jar:2.18.1]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [healthchecker.InstanceRepository] found for dependency [healthchecker.InstanceRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    ... 61 more


之前一切正常,我所做的更改是将InstanceInstanceRepositoryapplication移到了healthchecker,因为我只想在application中保留与控制器/网站相关的实用程序。由于我正在使用Spring-Boot 1.4.0Java 1.8,因此我没有进行任何beans配置。我该如何解决这个问题?

最佳答案

尝试添加@ComponentScan(“ healthchecker”),以便Spring知道其他bean的位置。

10-04 14:13