W3docs

Why is my Spring @Autowired field null?

There are several reasons why an @Autowired field in a Spring bean might be null:

There are several reasons why an @Autowired field in a Spring bean might be null:

  1. The field is missing the @Autowired annotation. Make sure that you are using the @Autowired annotation on the field. Note that @Autowired can also be placed on setter methods or constructors, which are fully supported and often recommended.
  2. The field is not in a Spring bean. @Autowired only works on fields that are part of a Spring bean. If you are trying to @Autowire a field that is not in a Spring bean, it will not be injected.
  3. The bean that the field is in has not been properly registered with the Spring application context. Make sure that the bean is either annotated with @Component or @Service, or is listed in the @ComponentScan annotation.
  4. There is no matching bean in the Spring application context to inject. Make sure that there is a bean of the correct type in the application context, or consider using the @Qualifier annotation to specify which bean to inject.
  5. The field is being accessed before it has been injected. @Autowired fields are injected by the Spring container after the bean's constructor runs, so accessing them in a constructor or static context will result in null. Use @PostConstruct methods or instance methods to safely access injected fields.

If you are still having trouble, try enabling debug logging for the Spring framework to get more information about what is happening during the injection process. You can do this by adding the following line to your application.properties file:


logging.level.org.springframework=DEBUG