100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Spring项目中value注解 @Value不能够读取到配置文件的值 无法成功注入值的问题解决

Spring项目中value注解 @Value不能够读取到配置文件的值 无法成功注入值的问题解决

时间:2021-08-07 05:15:10

相关推荐

Spring项目中value注解 @Value不能够读取到配置文件的值 无法成功注入值的问题解决

前言

今天在做项目的时候,我在监听器里面使用@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;@Overridepublic 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;@Configurationpublic class WebMvcConfig {//设置监听器,在服务上下文初始化的时候执行监听@Beanpublic 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;}@Overridepublic 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;@Configurationpublic class WebMvcConfig {@Value("${systemCpuProperties}")private String scp;//设置监听器,在服务上下文初始化的时候执行监听@Beanpublic ServletListenerRegistrationBean<SystemListener> systemListener(){ServletListenerRegistrationBean<SystemListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();servletListenerRegistrationBean.setListener(new SystemListener(scp));return servletListenerRegistrationBean;}}

问题完美解决,希望被采纳!!!

Spring项目中value注解 @Value不能够读取到配置文件的值 无法成功注入值的问题解决(超简单)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。