解决 springboot Interceptor @Autowired null技术
看如下代码块:
package com.lmlphp.nb.config;
import com.lmlphp.nb.interceptor.WebInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebInterceptor())
.addPathPatterns("/*")
.excludePathPatterns("/login");
super.addInterceptors(registry);
}
}
上面的代码看似非常简洁,其实是有一些问题的。当 WebInterceptor 类中使用了 @Autowired 的属性就会出现空指针错误。问题原因:拦截器加载的时间点在 springcontext 之前,所以在拦截器中注入值为 null,使用 Bean 注解提前加载即可解决。代码改成如下:
@Bean
public HandlerInterceptor getWebInterceptor(){
return new WebInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getWebInterceptor())
.addPathPatterns("/*")
.excludePathPatterns("/login");
super.addInterceptors(registry);
}
暂无