Spring uses @Autoried annotation failure solution in non-controller

Recently, when I was working on a project, I wanted to use the database in a util class I wrote. I thought it was safe, but I didn’t expect to report a null pointer when I started running.. Later, I found out that it was wrong to do so after searching the Internet. No, whether there is a solution, in fact, there is.

If you want to use the @Autowird annotation, you must first add the class you want to inject as a spring component, then how to add it, it's very simple, just use Spring's @Component

Next, you can happily use the @Autowired annotation, but now it is still reporting a null pointer, and then we create an init() method, and use the @PostConstruct annotation on it. After everything is completed, we still need a member variable of this class. When we use it, we only need to use member variables to call our injected Mapper or Service


This class can be used happily after the servlet is loaded~

Guess you like

Origin blog.csdn.net/JiayaoXu/article/details/79444355