SpringBoot攔截器不生效的問題解決
在使用 Spring Boot 開發(fā) Web 應(yīng)用時,我們常常需要使用攔截器(Interceptor)來對請求進行預(yù)處理。例如,驗證用戶是否登錄。然而,很多開發(fā)者會遇到一個常見的問題:攔截器配置了卻不生效。本文將討論一種常見的原因及其解決方案——將配置類移入正確的包下。
問題描述
我們創(chuàng)建了一個 LoginCheckInterceptor
類,并在 WebConfig
類中進行注冊。但是,啟動應(yīng)用后發(fā)現(xiàn)攔截器并沒有生效。
示例代碼:
LoginCheckInterceptor
類:
package com.itheima.interceptor; import com.alibaba.fastjson.JSONObject; import com.itheima.pojo.Result; import com.itheima.utils.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j @Component public class LoginCheckInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception { String url = req.getRequestURL().toString(); log.info("請求的url: {}", url); if (url.contains("login")) { log.info("登錄操作, 放行..."); return true; } String jwt = req.getHeader("token"); if (!StringUtils.hasLength(jwt)) { log.info("請求頭token為空,返回未登錄的信息"); Result error = Result.error("NOT_LOGIN"); String notLogin = JSONObject.toJSONString(error); resp.getWriter().write(notLogin); return false; } try { JwtUtils.parseJWT(jwt); } catch (Exception e) { e.printStackTrace(); log.info("解析令牌失敗, 返回未登錄錯誤信息"); Result error = Result.error("NOT_LOGIN"); String notLogin = JSONObject.toJSONString(error); resp.getWriter().write(notLogin); return false; } log.info("令牌合法, 放行"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle ..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion..."); } }
WebConfig
類:
package com.config; import com.itheima.interceptor.LoginCheckInterceptor; 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 WebConfig implements WebMvcConfigurer { @Autowired private LoginCheckInterceptor loginCheckInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**"); } }
解決方案
將 WebConfig
類移到 itheima
包下即可解決問題。原因在于 Spring Boot 的默認(rèn)包掃描機制。
原因分析
Spring Boot 使用 @SpringBootApplication
注解的主應(yīng)用類啟動應(yīng)用。該注解包含了 @ComponentScan
,默認(rèn)掃描主應(yīng)用類所在包及其子包中的所有組件。如果 WebConfig
類不在主應(yīng)用類所在包或其子包下,Spring Boot 將無法自動掃描到它,從而導(dǎo)致攔截器不生效。
解決方法
將 WebConfig
類移到 com.itheima
包下,確保其在主應(yīng)用類的掃描路徑內(nèi)。
調(diào)整后的目錄結(jié)構(gòu):
src/main/java └── com └── itheima ├── MyApplication.java ├── interceptor │ └── LoginCheckInterceptor.java └── config └── WebConfig.java
代碼調(diào)整
將 WebConfig
類從 com.config
包移到 com.itheima.config
包下:
package com.itheima.config; import com.itheima.interceptor.LoginCheckInterceptor; 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 WebConfig implements WebMvcConfigurer { @Autowired private LoginCheckInterceptor loginCheckInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**"); } }
其他解決方案
如果不想移動配置類,還可以通過以下方法顯式指定掃描路徑:
1. 使用 @ComponentScan
注解指定掃描包:
package com.itheima; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.itheima", "com.config"}) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
2. 使用 @Import
注解導(dǎo)入配置類:
package com.itheima; import com.itheima.config.WebConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @SpringBootApplication @Import(WebConfig.class) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
通過這些方式,可以確保 Spring Boot 正確掃描和加載攔截器配置類,使攔截器生效。
結(jié)論
在使用 Spring Boot 開發(fā) Web 應(yīng)用時,正確配置包掃描路徑非常重要。確保配置類在主應(yīng)用類的掃描路徑內(nèi),可以有效解決攔截器不生效的問題。希望這篇文章能夠幫助大家更好地理解 Spring Boot 的包掃描機制,并順利解決開發(fā)中遇到的問題。
到此這篇關(guān)于SpringBoot攔截器不生效的問題解決的文章就介紹到這了,更多相關(guān)SpringBoot攔截器不生效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Spring Cache時設(shè)置緩存鍵的注意事項詳解
在現(xiàn)代的Web應(yīng)用中,緩存是提高系統(tǒng)性能和響應(yīng)速度的重要手段之一,Spring框架提供了強大的緩存支持,通過??@Cacheable??、??@CachePut??、??@CacheEvict??等注解可以方便地實現(xiàn)緩存功能,本文給大家介紹了使用Spring Cache時設(shè)置緩存鍵的注意事項2025-01-01SpringBoot靜態(tài)資源CSS等修改后再運行無效的解決
這篇文章主要介紹了SpringBoot靜態(tài)資源CSS等修改后再運行無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Required?request?body?is?missing的問題及解決
這篇文章主要介紹了Required?request?body?is?missing的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12SpringBoot@Profile注解和Spring?EL(多環(huán)境注入)
為了方便, Spring還提供了 Profile機制, 使我們可以很方便地實現(xiàn)各個環(huán)境之間的切換,在使用DI來依賴注入的時候,能夠根據(jù)@profile標(biāo)明的環(huán)境,將注入符合當(dāng)前運行環(huán)境的相應(yīng)的bean,本文通過示例代碼介紹SpringBoot@Profile注解和Spring?EL,需要的朋友可以參考下2024-02-02