使用手动加载bean,
BeanFactory factory = WebApplicationContextUtils
.getRequiredWebApplicationContext(request.getServletContext());
userService = (UserService) factory
.getBean(“userService”);
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
/**
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
if(userService == null){
BeanFactory factory = WebApplicationContextUtils
.getRequiredWebApplicationContext(request.getServletContext());
userService = (UserService) factory
.getBean("userService");
}
}