Springboot中过滤器使用@Value获取配置文件值为null

在本地开发阶段,过滤器中使用@Value可以正常获取配置文件中的值

application.yaml配置文件如下:

app.system.id=20191010
app.service.secretkey=123456

过滤器配置

@WebFilter(urlPatterns = "/api/*", filterName = "SSOConfig")
public class SSOConfig implements Filter {

	 @Value("${app.system.id}")
 	 private String systemId;
	 
	 @Value("${app.service.secretkey}")
 	 private String secretKey;
 	 
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {

     }
	 	
	 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		//本地开发阶段是可以获取到值得
		System.out.println(systemId);
		System.out.println(secretKey);
        filterChain.doFilter(request, response); 
     }
     @Override
     public void destroy() {

     }
}

但是打成war包放在tomcat或金蝶apusic应用服务器上,@Value注入的值获取不到,systemId和secretKey都为null。这是因为先加载filter,然后再加载spring,所以注入的值为null,使用@Autowired注入bean的话,也是注入不了,值也为null。可以使用static变量,然后再为变量赋值的方法实现。

@Component
public class SSOUtil {

    public static String systemId;
    
    public static String secretKey;

    @Value("${app.system.id}")
    public void setSystemId(String systemId) {
        SSOUtil.systemId=systemId;
    }

    @Value("${app.service.secretkey}")
    public void setSecretKey(String secretKey) {
        SSOUtil.secretKey=secretKey;
    }
    
    public static String getApp() {
        return systemId+":"+secretKey;
    }
}
@WebFilter(urlPatterns = "/api/*", filterName = "SSOConfig")
public class SSOConfig implements Filter {
 	 
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {

     }
	 	
	 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		System.out.println(SSOUtil.getApp());
        filterChain.doFilter(request, response); 
     }
     @Override
     public void destroy() {

     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值