This article is a mirror article of machine translation, please click here to jump to the original article.

View: 16064|Reply: 2

[Source] Unable to inject @Autowired in Listener

[Copy link]
Posted on 4/4/2019 3:23:22 PM | | | |
Recently, when using the listener, I encountered the problem that spring could not be injected, the code is as follows, this task is always null, the package has obviously been swept away, but it cannot be injected.

The reason is as follows: the Listener listener cannot inject the bean using the @Resource of the Spring container or the method of @Autowired annotation, because, in the web server container,Neither Servlet, Filter, nor Listener are managed by Spring containersTherefore, we cannot directly use the Spring annotation method in these classes to inject the objects we need。 Here, the entire lifecycle of the servlet is handled by the servlet container. If you put it into a Spring container to create it, the servlet object can be created by the Spring container, but the servlet container may not know that the servlet exists because it is not in its own container. Therefore, the servlet is managed by the web server, not by spring.

Make the following modifications:

Taken from the context of spring, it solved the problem perfectly.


Springboot @Autowired fails to inject issues
https://www.itsvse.com/thread-6397-1-1.html
(Source: Architect_Programmer)






Previous:How to show and hide elements using Bootstrap4
Next:Java annotations@PostConstruct and detailed explanations and examples of @PreDestroy
 Landlord| Posted on 4/4/2019 3:54:53 PM |
Even if you set the entity listener to @Component, JPA is actually using just an instance of the class, not a Spring managed bean. That's why you get a NullPointerException. The accountHistoryRepo will always be empty.

https://stackoverflow.com/questi ... n-using-postpersist

The hack to inject dependencies on stateless beans is to define dependencies as "static", creating a setter method so that Spring can inject dependencies (assign them to static dependencies).

Declare dependencies as static.



Create a method so that Spring can inject it.



Resources:https://stackoverflow.com/questi ... -jpa-entitylistener
 Landlord| Posted on 4/4/2019 4:03:23 PM |
My solution is as follows:


Resources:The hyperlink login is visible.
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com