In a microservice project, you will encounter a situation where the @Autowired annotation fails. Here’s a summary of the @Autowired annotation failures.

The object that comes out of new

In the project, the @Component annotation was added to the corresponding class, but the object was actually new when used.

The object is null all the time. After checking, it is found that the Spring container does not manage the new object.

Spring is the default singleton, and if you annotate it, it’s Spring’s job to create the object.

If you simply new an object, it’s not up to Spring IOC to manage it.

There is no corresponding annotation

Annotations that can be handed to the Spring container to manage are:

@Service, @Component, @Configuration, and @Controller.

The static keyword modified the automatic injection object failed

For example, the static keyword is used in use:

 @Autowired private static TestController testController;
Copy the code

The acquired object will also be null because static is loaded before the Spring container-managed new object.

So if TestController is not created when you use it, it’s null.

The packet was not scanned

Use annotations in startup classes to scan:

@ComponentScan({**})

The Application annotated by @ComponentScan is not in the root directory, so the corresponding class cannot be searched.

This has been explained in many blogs, so I won’t repeat it here.

Other related problems, can refer to the article: blog.csdn.net/a532672728/…