0

Spring won't create an instance of bean. I have two classes

@Component
public class RestEventRegister {
    @Autowired
    private RestTemplate rest;
}

@Configuration
public class RestEventRegisterConfiguration {
@Bean
    public RestTemplate rest() {
        return new RestTemplate();
    }
}

Whenever I try use object rest inside RestEventRegister class it returns me nullpointer exception.

It was due I created RestEventRegister with new operator. I changed it so in main class, now I have:

@Configuration
public class MainConfiguration {
       @Bean
       public RestEventRegisterService restService() {
              return new RestEventRegisterService();
       }
}

@Component
public class Main {
       @Autowired
       public static RestEventRegisterService restService;

       public static void main (String[] args) {
             System.out.println(restService); // prints null
       }
}

but this @Autowired field still is null.

Hunteerq
  • 250
  • 1
  • 4
  • 15
  • An `@Autowired` field cannot be `null`, if that would be the case your application would blow up upon starting. If it is `null` you are creating a new instance of `RestEventListener` yourself instead of getting the Spring managed instance. – M. Deinum Jul 17 '18 at 07:02
  • Thank You so much for response! – Hunteerq Jul 17 '18 at 07:25

0 Answers0