前言
今天在做项目的时候,我在监听器里面使用@Value注解获取配置文件中的值,然后出现了空指针错误,表示值没有获取到。
- 然后我试了一下在controller层里面设置一个get方法,然后通过get方法获取,然后发现也是不行的。有点懵!
- 后来我发现了一个问题,我设置的Listener类和springboot不能共享spring的上下文,因为我这个类没有通过@Component注解加入到spring管理,所以获取不到值。
- 最后我想到了一个办法通过构造器传值。
初始代码
import com.infosec.itsramanage.listener.system.ThreadCpu; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class SystemListener implements ServletContextListener { @Value("${systemCpuProperties}") private String scp; @Override public void contextInitialized(ServletContextEvent sce) { ThreadCpu threadCpu = new ThreadCpu(scp); threadCpu.start(); } } import com.infosec.itsramanage.listener.SystemListener; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WebMvcConfig { //设置监听器,在服务上下文初始化的时候执行监听 @Bean public ServletListenerRegistrationBean<SystemListener> systemListener(){ ServletListenerRegistrationBean<SystemListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>(); servletListenerRegistrationBean.setListener(new SystemListener()); return servletListenerRegistrationBean; } }
修改后的代码
import com.infosec.itsramanage.listener.system.ThreadCpu; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class SystemListener implements ServletContextListener { private String scp; public SystemListener(String scp) { super(); this.scp = scp; } @Override public void contextInitialized(ServletContextEvent sce) { ThreadCpu threadCpu = new ThreadCpu(scp); threadCpu.start(); } } import com.infosec.itsramanage.listener.SystemListener; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WebMvcConfig { @Value("${systemCpuProperties}") private String scp; //设置监听器,在服务上下文初始化的时候执行监听 @Bean public ServletListenerRegistrationBean<SystemListener> systemListener(){ ServletListenerRegistrationBean<SystemListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>(); servletListenerRegistrationBean.setListener(new SystemListener(scp)); return servletListenerRegistrationBean; } }