Java工具類之@RequestMapping注解
一、前言
問題闡述:在某一場景下,我們的代碼在 Service 實現(xiàn)相同,但卻在 Controller 層訪問時卻希望不同的前綴可以訪問。如下 :/say/hello。我們這里希望在不借助任何外部服務的情況下 通過 /a/say/hello 和 /b/say/hello 都可以訪問到該接口,同時不想在 Controller 中寫兩個方法。
@RestController
@RequestMapping("say")
public class SayController {
@Autowired
private SayService sayService;
@RequestMapping("hello")
public String hello() {
return sayService.hello();
}
}
二、代碼實現(xiàn)
我們這里簡單說明一下思路:
1.在 Spring 服務啟動后, HandlerMapping 的實現(xiàn)類 RequestMappingHandlerMapping 會獲取到被 @RequestMapping等請求注解修飾的方法,并封裝成一個個 HandlerMethod 保存到 RequestMappingHandlerMapping#MappingRegistry 中(HandlerMapping 具有多個實現(xiàn)類,每個實現(xiàn)類具有不同規(guī)則)。
2.當 DispatcherServlet 接收到請求后會根據(jù) url 獲取 合適的 HandlerMapping 組成 HandlerExecutionChain(處理器執(zhí)行鏈),隨后通過 HandlerAdapter 來進行請求處理。而這里通過 HandlerMapping 會根據(jù)請求 URL 獲取到匹配的 HandlerMethod 進行方法調(diào)用。
因此我們這里有了兩種思路 :
1.在 Spring 加載 HandlerMethod 時設置當前 HandlerMethod 的匹配規(guī)則為 /a/say/hello/、/b/say/hello/,當 /a/say/hello/、/b/say/hello/ 請求訪問時可以與之匹配。
2.在請求處理的時候,通過攔截器將 /a/say/hello/、/b/say/hello/ 的訪問路徑匹配到 /say/hello 方法上。
本文選擇第一種思路(不過話說怎么想都是第一種好吧)做一個簡單demo示例,其實現(xiàn)如下:
// 自定義分發(fā)注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestRouter {
String[] value() default "";
}
package com.kingfish.springjdbcdemo.config;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @Author : kingfish
* @Email : kingfishx@163.com
* @Data : 2021/4/21 16:47
* @Desc : 路由 HandlerMapping 的實現(xiàn)
*/
@Component("handlerMapping")
public class RouterRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
// 在將 方法封裝成 HandlerMethod 時會調(diào)用此方法
@SneakyThrows
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
// 獲取 RequestRouter 注解
RequestRouter requestRouter = method.getAnnotation(RequestRouter.class);
if (requestRouter == null) {
requestRouter = handlerType.getAnnotation(RequestRouter.class);
if (requestRouter == null) {
for (Class<?> handlerTypeInterface : handlerType.getInterfaces()) {
if ((requestRouter = handlerTypeInterface.getAnnotation(RequestRouter.class)) != null) {
break;
}
}
}
}
// 調(diào)用父類,生成 RequestMappingInfo
RequestMappingInfo mappingForMethod = super.getMappingForMethod(method, handlerType);
if (requestRouter != null) {
// 如果 requestRouter 不為空,則進行路徑處理
String[] requestRouterValue = requestRouter.value();
PatternsRequestCondition condition = mappingForMethod.getPatternsCondition();
// 獲取當前方法匹配的路徑,隨即進行添加處理。
Set<String> patterns = condition.getPatterns();
Set<String> routerPatterns = patterns.stream()
// 拼接 請求路徑。這里可以自定義處理策略
.flatMap(pattern -> Arrays.stream(requestRouterValue).map(val -> "/" + val + pattern))
.collect(Collectors.toSet());
// 將拼接后的路徑添加到 RequestMappingInfo 中
patterns.addAll(routerPatterns);
}
return mappingForMethod;
}
}
@Configuration
public class SpringConfig {
@Bean
public DispatcherServlet dispatcherServlet(){
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// 禁止加載所有的handlerMapper,而只加載beanName 為 handlerMapper 的bean
dispatcherServlet.setDetectAllHandlerMappings(false);
return dispatcherServlet;
}
}
這里需要注意 :
1.HandlerMapping 在 Spring中有多個實現(xiàn),而 dispatcherServlet.setDetectAllHandlerMappings(false); 參數(shù)設置Spring 放棄加載多個 HandlerMapping,而只加載 beanName為 handlerMapping 的
2.HandlerMapping。RequestMappingInfo 包含 當前方法的諸多信息,其中就包含 什么樣請求路徑可以匹配到該方法,所以我們在這里獲取到 RequestRouter 的信息,并添加到匹配路徑上。
三、效果
在 方法上加上 @RequestRouter(value = {"a", "b"}) 注解
@RestController
@RequestMapping("say")
public class SayController {
@Autowired
private SayService sayService;
@RequestRouter(value = {"a", "b"})
@RequestMapping("hello")
public String hello() {
return sayService.hello();
}
}
/a/say/hello/、/b/say/hello/ 以及 /say/hello/ 都可以訪問


到此這篇關于Java工具類之@RequestMapping注解的文章就介紹到這了,更多相關Java RequestMapping內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spark SQL關于性能調(diào)優(yōu)選項詳解
這篇文章將為大家詳細講解有關Spark SQL性能調(diào)優(yōu)選項,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲2023-02-02
JavaWeb項目FullCalendar日歷插件使用的示例代碼
本篇文章主要介紹了JavaWeb項目FullCalendar日歷插件使用的示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08
Mybatis-plus實現(xiàn)join連表查詢的示例代碼
mybatis-plus在連表查詢上是不行的,如果需要連表查詢,就得乖乖的去寫xml文件了,本文介紹了mybatis-plus-join框架,它支持連表查詢,感興趣的可以了解一下2023-08-08
Spring Cloud 系列之負載均衡 Ribbon的示例代碼
SpringBoot統(tǒng)計一個Bean中方法的調(diào)用次數(shù)的實現(xiàn)步驟

