这段时间在写一个拦截器,发现很多文章上写Spring 拦截器和过滤器中自动注入为 null,基本上都是在说拦截器是在spring加载前进行加载的或是Spring注解扫描顺序的问题。
先看代码
package cn.com.easybugsystem.blocker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorAdapterConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}
package cn.com.easybugsystem.blocker;
import cn.com.easybugsystem.commom.UniformReturn;
import cn.com.easybugsystem.entity.EasyBuyUser;
import cn.com.easybugsystem.note.AdminLogin;
import cn.com.easybugsystem.note.NeedLogin;
import cn.com.easybugsystem.service.EasyBuyUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
EasyBuyUserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器测试");
//具体的业务
}
return true;
}
}
我这里用@Autowired注入了一个EasyBuyUserService类(可以实现注入),出现注入出现null的情况是因为LoginInterceptor类不是交给Spring来进行管理的,而是自己手动new出来的,要想实现注入,LoginInterceptor类也需要用注入来实现。不然Spring不会管LoginInterceptor里面的东西