Spring @Autowired 对象为 null

Luc*_*uca 4 spring unit-testing spock

我正在 spock 框架中编写一个规范类。

    @ContextConfiguration(classes = [MyServiceImplementation.class])
    class MyServiceSpecification extends Specification {

         @Autowired
         private MyService myServiceImplementation

         def "  " {
             //code
         }
    }
Run Code Online (Sandbox Code Playgroud)

该类MyServiceImplementation已注释@Service。我没有使用 XML 配置。MyServiceImpl是接口的实现:MyService

为什么自动装配的对象为myServiceImplementation空?

我尝试使用ComponentScan,但仍然不起作用。

Leo*_*ngs 7

首先,您需要在类路径上同时拥有spock-core和。spock-spring其次,@ContextConfiguration(classes=采用配置类列表,而不是 bean 类。

@ContextConfiguration(classes = [MyConfig.class])
class MyServiceSpecification extends Specification {

     @Autowired
     private MyService myServiceImplementation

     def "  " {
         //code
     }
}

// You could also define @ComponentScan here
class MyConfig {
    @Bean
    MyService myService() {
      return new MyServiceImplementation();
    }
}
Run Code Online (Sandbox Code Playgroud)