【问题标题】:Spring @Autowired object is nullSpring @Autowired 对象为空
【发布时间】:2017-09-18 13:51:49
【问题描述】:

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

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

         @Autowired
         private MyService myServiceImplementation

         def "  " {
             //code
         }
    }

MyServiceImplementation 类被注解为@Service。我没有使用 XML 配置。 MyServiceImpl 是接口的一个实现:MyService。

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

我尝试过使用ComponentScan,但还是不行。

【问题讨论】:

  • 听起来你在代码中的某处执行“新”MyServiceSpecification(或者 Spock 正在这样做)!
  • 有什么解决方法吗?我看不出这会如何影响该字段的空值
  • 您是否使用 Spock 弹簧模块 (spockframework.org/spock/docs/1.1/…)?

标签: spring unit-testing spock


【解决方案1】:

首先,您需要在类路径中同时拥有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();
    }
}

【讨论】:

  • 我应用了更改并且它工作了,感谢您的解决方案
猜你喜欢
  • 2018-09-25
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多