Spring boot在过滤器/拦截器中使用配置文件中的数据@Value @Autowired笔记

当在spring boot的拦截器/过滤器中要读取配置文件时,最常用的@Component 搭配@Value 或者 @Autowired 都无法读取到值,究其原因是因为加载顺序的问题,简单来说,listener->filter->servlet,所以过滤器/拦截器在初始化的时候,那些值和类还没加载,当然就是空了,这里推荐两种方法。

**

其一:工具类读取批量

**

首先 声明一个工具类,读取配置文件中的同级下的多个变量

package com.test.cas;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@EnableAutoConfiguration
@ConfigurationProperties(prefix = "cas.url" ) // yml中的前缀
@Primary
public class CasUrlConfig {

    // 登录地址
    private String loginUrl; // 在我的yml中为 cas:url:loginUrl (不带格式,注意错行)
  
    // 登出地址
    private String logoutUrl; // 在我的yml中为 cas:url:logoutUrl  (不带格式,注意错行)

    public CasUrlConfig() {
        super();
    }
    
    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    public String getLogoutUrl() {
        return logoutUrl;
    }

    public void setLogoutUrl(String logoutUrl) {
        this.logoutUrl = logoutUrl;
    }
}

然后,在过滤器中引用此工具类

package com.test.interceptor;

public class InterceptorConfig implements HandlerInterceptor {

    @Autowired
    private CasUrlConfig config;  // 此处通过Autowired引用
    
    /**
     * 进入controller层之前拦截请求
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        log.info("---------------------开始请求拦截----------------------------");
        // 这里进行拦截处理操作
        config.getLoginUrl();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---------------视图渲染之后的操作-------------------------0");
    }
}

到这里还不算完,还要声明过滤器,才能读取到值

package comtest.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public HandlerInterceptor getDataInterceptor(){
        return new InterceptorConfig();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册自定义拦截器,添加拦截路径和排除拦截路径
        registry.addInterceptor(getDataInterceptor()).addPathPatterns("/**");
    }


}

这样就可以了

**

其二,读取配置文件中的单个变量

**

此处我是在过滤器中使用的,并不限定使用位置,只是我的例子而已

package com.test.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.feilong.core.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class RefererFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 1L;
	
    @SuppressWarnings("unused")
    private FilterConfig filterConfig;

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// 从这里开始,先获取容器
		ServletContext context = request.getServletContext();
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
		// 再读取配置文件中的变量
		Environment environment = ctx.getBean(Environment.class);
		String soUrl = environment.getProperty("cas.url.loginUrl");
		// 进行自定义处理

		chain.doFilter(request, response);

	}

	@Override
	public void destroy() {
		this.filterConfig = null;
	}
}

因为近些时间经常遇到这些情况,所以记录下来供以后查阅,节省时间。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值