Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Autowired object is null

I'm writing a specification class in spock framework.

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

         @Autowired
         private MyService myServiceImplementation

         def "  " {
             //code
         }
    }

The class MyServiceImplementation is annotated @Service. I'm not using XML configuration. MyServiceImpl is an implementation of the interface: MyService.

Why is the autowired object myServiceImplementation null?

I tried using ComponentScan and it still didn't work.

like image 286
Luca Avatar asked Sep 21 '25 12:09

Luca


1 Answers

First, you need to have both spock-core and spock-spring on the classpath. Second, @ContextConfiguration(classes= takes a list of configuration classes, not bean classes.

@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();
    }
}
like image 168
Leonard Brünings Avatar answered Sep 23 '25 00:09

Leonard Brünings