How to solve the problem of not injecting javabean? through annotations

function description:
when tomcat starts, a thread is started at the same time. Currently, there is no problem with thread startup, but a null pointer exception is caused due to the inability to inject javabean,. The javabean to be injected is encapsulated by itself and is used to implement specific functions. The class is annotated with @ Component and is also within the scanning range of package-scan. (note: SSM framework used)

the code is as follows:

@Controller
public class UDPServer implements ServletContextListener {

    // Bean
    @Autowired
    UDPThread udpThread;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // Bean
        udpThread.execute();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
Mar.21,2021

first of all, you need to know what ServletContextListener is? Why is it invalid?
ServletContextListener use details

secondly, why not Google or Baidu first?
the answer is here @ Autowired in ServletContextListener

. < hr >

Why don't you search for this question first

Google


the problem is solved, and the specific process is as follows:

1. Add:

to contextInitialized
UDPThread udpThread = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContextEvent.getServletContext()).getBean(MyBean.class);

2. Add:

to web.xml
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>cn.env.web.util.UDPServer</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/config/Spring-*.xml</param-value>
  </context-param>

refer to the first step written by stackoverflow, and you also need to configure web.xml, or tomcat cannot start: Link description

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e59d92-4555e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e59d92-4555e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?