【问题标题】:@JdbcTest detect class annotated @SpringBootApplication@JdbcTest 检测类注解 @SpringBootApplication
【发布时间】:2017-03-10 15:51:53
【问题描述】:

我已经在以下项目结构中尝试了@JdbcTest

.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           ├── Application.java
    │   │           ├── repository
    │   │           │   └── DemoRepository.java
    │   │           └── service
    │   │               └── DemoService.java
    │   └── resources
    │       └── application.properties
    └── test
        └── java
            └── com
                └── example
                    ├── ApplicationTests.java
                    └── repository
                        └── DemoRepositoryTests.java

DemoRepository.java(测试目标)

package com.example.repository;

import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.stereotype.Repository;

@Repository
public class DemoRepository {

    private final JdbcOperations jdbcOperations;

    DemoRepository(JdbcOperations jdbcOperations) {
        this.jdbcOperations = jdbcOperations;
    }

    public int findNumber() {
        return jdbcOperations.queryForObject("SELECT 1",int.class);
    }

}

DemoRepositoryTests.java(测试类)

package com.example.repository;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@JdbcTest
@Import(DemoRepository.class)
public class DemoRepositoryTests {

    @Autowired
    private DemoRepository repository;

    @Test
    public void findNumber() {
        Assertions.assertThat(repository.findNumber()).isEqualTo(1);
    }

}

Application.java(类注解@SpringBootApplication

package com.example;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.example.service.DemoService;

@SpringBootApplication
public class Application {

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

    @Bean
    public CommandLineRunner demo(DemoService service) {
        return args -> System.out.println("Number:" + service.findNumber());
    }

}

我已经执行了DemoRepositoryTests。然后出现以下错误。

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-10 23:55:44.092 ERROR 9375 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method demo in com.example.Application required a bean of type 'com.example.service.DemoService' that could not be found.


Action:

Consider defining a bean of type 'com.example.service.DemoService' in your configuration.

2017-03-10 23:55:44.100 ERROR 9375 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@1442d7b5] to prepare test instance [com.example.repository.DemoRepositoryTests@3c0a50da]

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47) ~[spring-boot-test-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.7.RELEASE.jar:4.3.7.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.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.7.RELEASE.jar:4.3.7.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.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.7.RELEASE.jar:4.3.7.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.7.RELEASE.jar:4.3.7.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo' defined in com.example.Application: Unsatisfied dependency expressed through method 'demo' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.service.DemoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 28 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.service.DemoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 46 common frames omitted

重现项目是

是这种行为的规范吗?

前置条件

  • Spring Boot 1.5.2.RELEASE

【问题讨论】:

    标签: spring-boot spring-boot-test


    【解决方案1】:

    我在尝试使用 @JdbcTest 为我的存储库设置测试方法时遇到了同样的问题。

    查看 Spring Boot Reference 文档和 Andy Wilkinson 引用的源代码后,这里是我的解决方案。

    1. 通过声明带有@Configuration 注释的内部类,防止@JdbcTest 搜索带有@SpringBootApplication 注释的主配置和其他@Configuration。根据以下代码,内部 @Configuration 类将覆盖为当前为空的主要配置。
    @RunWith(SpringRunner.class)
    @JdbcTest
    @Import({TestConfiguration.class, DemoRepository.class})
    @AutoConfigureTestDatabase
    @TestPropertySource(properties = {"spring.datasource.schema=classpath:dbschema.sql"})
    public class DemoRepositoryTest {
      //This is the main key to override the search done by @JdbcTest to
      //those annotated with @SpringBootApplication, other @Configuration
      @Configuration
      @EnableAutoConfiguration 
      static class Config {
      }
      @Autowired
      DemoRepository repository;
      @Before
      public void setUp() throws Exception {
      ...
      }
      @Test
      public void findOne() throws Exception {
      ...
      }
    }
    
    1. 我正在使用NamedParameterJdbcDaoSupport,所以这是我如何配置DataSource
    @TestConfiguration
    public class TestConfiguration {
        //SpringBoot Test AutoConfig will inject the memory db here.
        @Autowired
        DataSource dataSource;
    
        @Bean
        public NamedParameterJdbcDaoSupport jdbcDaoSupport() {
    
            NamedParameterJdbcDaoSupport support = new NamedParameterJdbcDaoSupport();
            support.setDataSource(dataSource);
    
            return support;
        }
    }
    
    1. DemoRepository.java
    @Repository
    public class DemoRepository {
    
        private final NamedParameterJdbcTemplate jdbcTemplate;
    
        public DemoRepository(NamedParameterJdbcDaoSupport jdbcDaoSupport) {
    
            this.jdbcTemplate = jdbcDaoSupport.getNamedParameterJdbcTemplate();
    
        }
    
    1. pom.xml, h2 中声明 Memory DB Driver 作为示例:

      <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
          <scope>test</scope>
          <version>1.4.196</version>
      </dependency>
      

    【讨论】:

    • 这并不能真正回答问题。如果您有其他问题,可以点击 进行提问。一旦你有足够的reputation,你也可以add a bounty 来引起对这个问题的更多关注。 - From Review
    • 第 1 点确实如此。我已经更新了相同的描述。
    【解决方案2】:

    我为此找到了一个错误原因。

    原因

    SpringBootTestContextBootstrapper(@JdbcTest 使用的TestContextBootstrapper) 查找注释为@SpringBootConfiguration(或@SpringBootApplication)的类。

    SpringBootTestContextBootstrapper#getOrFindConfigurationClasses:

    protected Class<?>[] getOrFindConfigurationClasses(
            MergedContextConfiguration mergedConfig) {
        Class<?>[] classes = mergedConfig.getClasses();
        if (containsNonTestComponent(classes) || mergedConfig.hasLocations()
                || !mergedConfig.getContextInitializerClasses().isEmpty()) {
            return classes;
        }
        Class<?> found = new SpringBootConfigurationFinder()
                .findFromClass(mergedConfig.getTestClass()); // #### This !! ###
        Assert.state(found != null,
                "Unable to find a @SpringBootConfiguration, you need to use "
                        + "@ContextConfiguration or @SpringBootTest(classes=...) "
                        + "with your test");
        logger.info("Found @SpringBootConfiguration " + found.getName() + " for test "
                + mergedConfig.getTestClass());
        return merge(found, classes);
    }
    

    SpringBootConfigurationFinder#findFromClass 首先从与测试类相同的包中查找。如果不存在同一个包,则从父包递归查找。

    SpringBootConfigurationFinder#scanPackage:

    private Class<?> scanPackage(String source) {
        while (source.length() > 0) {
            Set<BeanDefinition> components = this.scanner.findCandidateComponents(source); // ### Find ###
            if (!components.isEmpty()) {
                Assert.state(components.size() == 1,
                        "Found multiple @SpringBootConfiguration annotated classes "
                                + components);
                return ClassUtils.resolveClassName(
                        components.iterator().next().getBeanClassName(), null);
            }
            source = getParentPackage(source); // ### Fallback ###
        }
        return null;
    }
    

    可能的解决方案(变通方法?)

    1. 删除注解@SpringBootApplication@SpringBootConfiguration 的类上的bean 定义和依赖注入。
    2. 在测试类上加载自定义配置类(未注解@TestConfiguration)。

      例如)使用静态内部类

      @RunWith(SpringRunner.class)
      @JdbcTest
      @Import(DemoRepository.class)
      public class DemoRepositoryTests {
          // ...    
          @Configuration
          static class Config { // ### Add
          }
      }
      

      例如)使用共享配置类进行测试

      @JdbcTest
      @Import(DemoRepository.class)
      @ContextConfiguration(classes = TestConfig.class) // ### Add
      public class DemoRepositoryTests {
          // ...    
      }
      
    3. 创建@SpringBootApplication 类以测试到同一个包中。

      package com.example.repository;
      
      import org.springframework.boot.SpringBootConfiguration;
      
      @SpringBootApplication
      class RepositoryTestApplication {
      
      }
      
    4. 还有更多...?

    我认为解决方案 3 是不错的选择。

    【讨论】:

      【解决方案3】:

      你没有一个只有 @JdbcTest 和 @Import 的应用程序上下文,你需要做同样的事情,因为你的 ApplicationTests 是声明 @SpringBootTest

      【讨论】:

      • 感谢您的评论!为什么需要它?我想知道原因!!
      • 对不起,这个答案是错误的。也不需要使用@SpringBootTestHere 是 Spring Boot 自己的集成测试之一,仅使用 @JdbcTest
      • @AndyWilkinson 感谢您的评论!我在自己的答案中添加了新的可能解决方案(解决方案 3)。
      • 对不起@AndyWilkinson,我知道没有必要使用@SpringBootTest 来测试JDBC 集成,但是在这种情况下我们需要解决这个错误异常:Error creating bean with name 'demo' defined in com.example.Application,我的建议是一种解决方法它。如果在这种情况下有任何问题,请纠正我,并感谢您对我的回答的反馈。我在这里查看了作者的源代码演示 - github.com/kazuki43zoo/spring-boot-issues/tree/gh-8566/gh-8566
      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2016-02-10
      • 2020-04-27
      • 1970-01-01
      • 2017-08-07
      • 2021-11-30
      • 2017-05-30
      相关资源
      最近更新 更多