Spring @Autowired对象为空。

4

我正在使用Spock框架编写规范类。

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

         @Autowired
         private MyService myServiceImplementation

         def "  " {
             //code
         }
    }

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

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

我尝试使用ComponentScan,但仍然无法工作。


听起来你的代码中有地方在使用'new' MyServiceSpecification(或者是Spock在使用)! - MystyxMac
有没有什么解决方法?我看不出这会如何影响该字段的空值。 - Luca
你是否使用 Spock Spring 模块(http://spockframework.org/spock/docs/1.1/all_in_one.html#_spring_module)? - MystyxMac
1个回答

7

首先,您需要将spock-corespock-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();
    }
}

我应用了更改,它起作用了,感谢解决方案。 - Luca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接