Filter使用@Autowired失败为null

可使用如下方式进行注入

   public class ControllerFilter implements Filter {
    	@Autowired
    	private LogsPutDataBase logsPutDataBase;
    	@Override
    	public void init(FilterConfig arg0) throws ServletException {
    		ServletContext servletContext = arg0.getServletContext();
    		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    		logsPutDataBase = (LogsPutDataBase)ctx.getBean("logsPutDataBase");
    	}
		
		public void destroy () {
		}
		
		public void doFilter(ServletRequest arg0, ServletResponse arg1,  
            FilterChain arg2){
			......
			return;
		}
}

原因:

在Spring中,web应用启动的顺序是:listener->filter->servlet,先初始化listener,然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,因为filter初始化时,注解的bean还没初始化,没法注入。

@RefreshScope @Configuration public class CasConfiguration extends CasClientConfigurerAdapter { private final static Logger log = LoggerFactory.getLogger(CasConfiguration.class); @Autowired private CasProperties casProperties; @Autowired(required = false) private DebugUserService debugUserService; @Override public void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) { super.configureAuthenticationFilter(authenticationFilter); if (casProperties.getUrlPatterns() != null) { authenticationFilter.setUrlPatterns(casProperties.getUrlPatterns()); } else { log.warn("没有设置gate.cas.url-patterns,使用: [/*]"); authenticationFilter.setUrlPatterns(Collections.singletonList("/*")); } AuthenticationFilter authFilter = (AuthenticationFilter) authenticationFilter.getFilter(); authFilter.setIgnoreUrlPatternMatcherStrategyClass(new UrlPatternMatcherStrategy() { @Override public boolean matches(String s) { // s: http://JCODE-PC.lan:8080/actuator/health // s: http://localhost:8080/test // 开启调试时忽略所有拦截 if (debugUserService != null && debugUserService.inDebugMode()) { return true; } return ignoreUrlPatterns(s); } @Override public void setPattern(String s) { log.debug("CAS UrlPatternMatcherStrategy set pattern: {}", s); } }); } public boolean ignoreUrlPatterns(String requestUri) { List<String> ignoreUrlPatterns = casProperties.getIgnoreUrlPatterns();//忽略包括哪些路径 if (ignoreUrlPatterns.size() == 0) { return false; } for (String pattern : ignoreUrlPatterns) { if (requestUri.contains(pattern)) { return true; } } return false; } }详解该代码
06-14
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值