~/spring/spring-boot-autowire-bean-not-found.md

Spring Boot - Fixing Autowire Bean Not found

2 min readJanuary 12, 2022by Gorav Singal#spring#spring-boot#autowire
// TL;DR

Resolve Spring Boot autowire failures by ensuring the bean's package is included in component scanning via @ComponentScan or proper package structure.

Spring Boot - Fixing Autowire Bean Not found

Introduction

In a Spring boot app, we tend to use @Autowire annotation, so that Spring can inject our dependency. It helps in not writing the constructor explicitly and developer doesn’t need to take care of from where this bean is coming.

Example Code

  @Autowired
	private UserService userService;

At some point, we encounter errors like below:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field <your-field> in com.your-package.controllers.MyController required a bean of type 'com.your-package.service.UserService' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.your-package.service.UserService' in your configuration.

Probable Reasons and Solutions

@Autowire searches in the spring context for the bean.

There might be few probable reasons of this error:

  • You have not defined the bean anywhere (Unless you declared the class with annotations like service/component etc, see next point). If you are using xml spring context, define the bean there.

  • You forgot to declare the class with annotations like: @Component, @Service, @Controller, @Configuration, @Repository, there might be more

(Note: above annotations are for respective purposes, so use them as per use-case)

  • You have initialized the class by explicit constructor (by new), Autowire will not work there. As, that instance will not be registered to Spring for dependency injection.

So, do not initialize a class by explicit constructor. Let spring handle it for you.

  • You have used @ComponentScan, but in wrong package. Specify the correct package there. You can specify multiple packages there as well.
@ComponentScan({ "com.path1", "com.path2", "com.path3"})
  • Your spring-boot main class (@SpringBootApplication), is located in some inner package. By default, spring boot main class, scans the child packages. So, if you have defined your main class in some inner package, move it to the top package.

  • There might be mutiple beans of same class. You need to help @Autowire, that which bean name you want to take.

Use:

  @Autowired
  @Qualifier("userService")
	private UserService userService;
  • You can specify @ComponentScan in your main class @SpringBootApplication
@SpringBootApplication(scanBasePackages = { "com.path1", "com.path2"})
public class MyApplication {

	public static void main(String[] args) throws InterruptedException {
		
		SpringApplication.run(MyApplication.class, args);
	}
}

OR

@SpringBootApplication
@ComponentScan({ "com.path1", "com.path2"})
public class MyApplication {

	public static void main(String[] args) throws InterruptedException {
		
		SpringApplication.run(MyApplication.class, args);
	}
}

Hope it helps.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Spring - Learn Multiple Ways to use PackageScan Annotation

Spring - Learn Multiple Ways to use PackageScan Annotation

Introduction In this post, we will see multiple ways to use annotation…

Fix: SAML Message Intended Destination Did Not Match Recipient

Fix: SAML Message Intended Destination Did Not Match Recipient

Introduction I was trying to integrate Okta with Spring, and when I deploy the…

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Introduction Java log4j has many ways to initialize and append the desired…

Java - Union and Intersection of two lists

Java - Union and Intersection of two lists

Suppose you have two lists, and you want Union and Intersection of those two…

Linkage Error Loader Constraint Violation - JUnit test case development issue

Linkage Error Loader Constraint Violation - JUnit test case development issue

Its good to write unit tests cases, and this part is mostly forgotten by…

How to mock a constructor - Junit test case development issues

How to mock a constructor - Junit test case development issues

While writing JUnit test cases, we encounter cases like we want to initialize a…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…