java.lang.NullPointerException: null


springboot 中一個空指針的錯誤提示:

2019-03-25 11:26:25.769 ERROR 8896 --- [nio-8680-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]  :Servlet.service() for servlet [dispatcherServlet] in context with path /ding threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null

at jlsky.auth.AuthInterceptor.preHandle(AuthInterceptor.java:55) ~[classes/:na]

(省略余下的 tomcat的各種提示信息。)

事情是這樣的,參照 https://www.jianshu.com/p/e88d3f8151db 做了個自定義注解和攔截器的權限模塊。但是一運行到 @Autowired 注入的方法就報錯。

攔截器的部分代碼如下:

public class AuthInterceptor implements HandlerInterceptor {
@Autowired RoleConfirmImpl roleConfirm;

@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,Object obj) throws ResultException {
String token = req.getHeader("token"); // 從請求中獲取 token
if(!(obj instanceof HandlerMethod)){ //如果不是映射到方法,直接通過。
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) obj;
Method method = handlerMethod.getMethod();

//檢查有沒有需要驗證用戶授權的注解
if(method.isAnnotationPresent(AuthToken.class)){
AuthToken authToken = method.getAnnotation(AuthToken.class);
if(authToken.required()){
//執行認證
if(token == null){
throw new ResultException(ResultCode.LOGIN_NOTOKEN);
}
//verify token,獲取 token中的 userid
int userid = JwtUtil.verifyUserId(token);
log.info("userid: "+ userid);
roleConfirm.belong(userid,authToken.role());
return true;
}else{
return false;
}
}
return true; //沒有應用注解的訪問,許可通過。
}
起初,是通過接口間接訪問的方法。去掉接口這個環節,問題依舊。
再后來在方法上添加了 static 解決問題。
(如果在接口的方法上加 static,那么就需要直接寫方法體,也就失去了定義接口意義。)

雖然問題解決了,但是總覺得這個方法有點LOW。其實我也嘗試了加注解或者放到main方法定義的掃描路徑下,都不行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM