springboot

Spring Boot: What to do when Autowired stops working

That’s weird! Suddenly, you try to inject a dependency in your Spring Boot application, but it’s like @Autowired stopped working.

You will see this in several ways. IntelliJ will provide a warning from the Spring plugin, which says “Could not autowire. No beans of ‘YourBeanName’ type found.”

At runtime, Spring itself will fail with a message like:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.scottshipp.www.YourBeanName' available: expected at least 1 bean which qualifies as autowire candidate.

If this behavior looks familiar, please read on.

The Solution
Most likely what is happening is pretty simple. Somewhere you’ve defined a class with the @SpringBootApplication annotation and a main method. Which package is this class in? If it is not in the base package above all the components, services, repositories, etc. that you want to autowire, then you will get the dreaded “No qualifying bean of type…” error. Guaranteed!

The simple solution is simply to move that class to the base package, and all should be right with the world again. Hope its helpful.

One thought on “Spring Boot: What to do when Autowired stops working

  1. Stephane

    Spring Boot doesn’t scan the whole classpath (that would be rather dumb). If you structure your project in a sensible fashion, this shouldn’t be a problem (see the documentation See also the documentation about this: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-locating-the-main-class).

    If you want to deviate from that, that’s fine and there is no need to move the class elsewhere if you don’t want to. Just configure @ComponentScan to also scan additional packages.

Leave a Reply

Your email address will not be published. Required fields are marked *