Spring@Autowired对象为空
我正在spock框架中编写一个规范类Spring@Autowired对象为空,spring,unit-testing,spock,Spring,Unit Testing,Spock,我正在spock框架中编写一个规范类 @ContextConfiguration(classes = [MyServiceImplementation.class]) class MyServiceSpecification extends Specification { @Autowired private MyService myServiceImplementation def " " {
@ContextConfiguration(classes = [MyServiceImplementation.class])
class MyServiceSpecification extends Specification {
@Autowired
private MyService myServiceImplementation
def " " {
//code
}
}
类MyServiceImplementation
被注释为@Service
。我没有使用XML配置MyServiceImpl
是接口的实现:MyService
为什么自动连线对象myServiceImplementation
null
我尝试使用
ComponentScan
,但仍然不起作用。首先,您需要在类路径上同时使用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();
}
}
听起来你在代码中的某个地方(或者Spock正在这么做)做“新建”MyServiceSpecification!有什么解决方法吗?我看不出这会如何影响此字段的空值。你使用Spock Spring模块()吗?我应用了更改,它成功了,感谢您的解决方案