Spring-boot listener’s @autowire
is not working on recent versions
sample code link https://github.com/maafshar/listenerautowire
When using 2.3.1.RELEASE of Spring-boot everything is ok.
@WebListener public class Listener implements ServletContextListener {
@Autowired private Environment env;
@Override public void contextInitialized(ServletContextEvent sce) {
try {
if (env == null) // is false
When using 2.6.2 of Spring-boot the env will be null
change pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version><!-- ********************* 2.3.1.RELEASE - 2.6.2 ********************* -->
<relativePath/>
</parent>
Comment From: snicoll
Thanks for the sample. Autowiring isn't available as of Spring Boot 2.4.0
already. I've only found this section in the release notes but I am not sure it is related.
Comment From: maafshar
replacing @WebListener with @Component solved the problem, but as you mentioned from 2.4.0 the problem exists.
Comment From: wilkinsona
As @snicoll suspected, this is due to the changes in Spring Boot 2.4 to allow @WebListener
s to register servlets and filters. The change in 2.4 requires the Servlet container to be responsible for creating the listener so Spring-based dependency injection is no longer available.
Generally speaking, @ServletComponentScan
is intended for registering third-party components where you can't modify the code. If you're in a position to use @Autowired
and the like then you should use @Component
. An exception to this is where you need to be able to register servlets and filters from your listener. @WebListener
should be used in this case.
I've updated the release notes for 2.4.