创建bean时出错 - Spring Boot

时间:2016-09-26 03:34:23

标签: java spring mongodb spring-mvc spring-boot

我喜欢Spring Boot,我真的很喜欢!我正在使用Spring-Boot 1.4.1, Java 8 and MongoDB,我定义了以下类。

package builds;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BuildsRepository extends MongoRepository<Build, String> {

    List<Build> findByProvider(String provider);

    List<Build> findByDeployer(String deployer);
}

然后是模型Builds

package builds;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

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;
import com.google.gson.Gson;

@Document(collection = "builds")
public class Build {

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

    @NotNull
    @Size(min=2)
    private String configuration;

    @NotNull
    private String provider;

    @NotNull
    private String deployer;

    @NotNull
    @Min(0)
    private Integer instances;

    public Build() {
    }

    public Build(String configuration, Integer instances, String provider, String deployer) {
        this.id = new ObjectId().toHexString();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        this.date = dateFormat.format(new Date());
        this.configuration = configuration;
        this.provider = provider;
        this.instances = instances;
        this.deployer = deployer;
    }

    public Integer getInstances() {
        return this.instances;
    }

    public void setInstances(Integer instances) {
        this.instances = instances;
    }

    public String getProvider() {
        return this.provider;
    }

    public void setProvider(String provider) {
        this.provider = provider;
    }

    public void setDeployer(String deployer) {
        this.deployer = deployer;
    }

    public String getDeployer() {
        return this.deployer;
    }

    public String getDate() {
        return this.date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getConfiguration() {
        return this.configuration;
    }

    public void setConfiguration(String configuration) {
        this.configuration = configuration;
    }

    @Override
    public String toString() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }
}

最后,我在Build中使用BuildRepositoryBuildsController

package tools;

@Controller
public class BuildsController {

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

    @Autowired
    private BuildsRepository buildsRepository;

    public BuildsController() {
    }

    /*
     * Add the builds url page
     */
    @GetMapping("/builds")
    public String index(Model model) {
        model.addAttribute("build", new Build());
        return "builds";
    }

    /**
     * 
     * @param object
     * @return
     */
    @PostMapping("/builds")
    public Build deploy(@ModelAttribute Build build) {
        this.buildsRepository.save(build);
        return build;
    }
}

但是,对于我以类似方式创建的DocumentService的每个模型,我已经得到了相同的错误,所以我认为必定存在配置问题:

    Caused by: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buildsController': Unsatisfied dependency expressed through field 'buildsRepository': No qualifying bean of type [builds.BuildsRepository] found for dependency [builds.BuildsRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [builds.BuildsRepository] found for dependency [builds.BuildsRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buildsController': Unsatisfied dependency expressed through field 'buildsRepository': No qualifying bean of type [builds.BuildsRepository] found for dependency [builds.BuildsRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [builds.BuildsRepository] found for dependency [builds.BuildsRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[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 [builds.BuildsRepository] found for dependency [builds.BuildsRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566) ~

我的Application课很简单:

package tools;

@SpringBootApplication
@EnableMongoRepositories(basePackages = "tools")
public class Application implements CommandLineRunner {

    /* Use the User collections */
    @Autowired
    private UserRepository repository;

    public final static Logger logger = Logger.getLogger(Application.class);

    public static void main(String[] args) throws Throwable {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        this.repository.deleteAll();
        // ..
    }
 }

有人能告诉我如何解决这个问题吗?我最近因为太过蛇咬伤了。

*修改我已将@EnableMongoRepositories(basePackages = "tools")添加到Application.java课程。

3 个答案:

答案 0 :(得分:2)

问题是Application类在tools包中,而其他bean在builds包中。他们处于同一水平。因此,自动配置仅适用于tools包和tools包内的所有包。为了使一切正常,请移动Application类,即默认包(builds包之上的一个包级别)或builds包(与其他bean相同的级别),一切都应该有效。在这种情况下,由于@EnableMongoRepositories注释启用了自动配置,因此您甚至不需要@SpringBootApplication注释。

答案 1 :(得分:1)

我相信你在控制器类

中缺少注释@EnableMongoRepositories

@EnableMongoRepositories(basePackages =&#34;工具&#34)

答案 2 :(得分:1)

我可以看到存储库和模型类的包名是版本。因此,请提供如下所示的包名称以启用存储库

@EnableMongoRepositories(basePackages = "builds")