[英]How to modify RequestMapping value based on custom annotation
我想寫類似(簡體)的東西
@MyAnnnotationForPrefix("/foo1")
@RestController
@RequestMapping("/bar")
public class Test1Controller{
...
}
@MyAnnnotationForPrefix("/foo2")
@RestController
@RequestMapping("/bar")
public class Test2Controller{
...
}
並通過url /foo1/bar
和/foo2/bar
url訪問它們。 我應該在哪里放置用於處理@MyAnnnotationForPrefix
邏輯?
似乎是這樣完成的(如果此解決方案有任何缺點,請糾正我,我會很樂意接受您的回答)
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 java.lang.reflect.Method;
public class MyPrefixedRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
if (mappingInfo == null) {
return null;
}
MyAnnnotationForPrefix myAnnotation = handlerType.getAnnotation(MyAnnnotationForPrefix.class);
if (myAnnotation == null) {
return mappingInfo;
}
PatternsRequestCondition patternsRequestCondition =
new PatternsRequestCondition(myAnnotation.getValue())
.combine(mappingInfo.getPatternsCondition());
return new RequestMappingInfo(mappingInfo.getName(),
patternsRequestCondition,
mappingInfo.getMethodsCondition(),
mappingInfo.getParamsCondition(),
mappingInfo.getHeadersCondition(),
mappingInfo.getConsumesCondition(),
mappingInfo.getProducesCondition(),
mappingInfo.getCustomCondition()
);
}
}
另外,您需要將此RequestMappingHandlerMapping添加到webmvc配置中。 在spring-boot中,定義了bean:
@Component
public class MyPrefixedWebMvcRegistrations extends WebMvcRegistrationsAdapter {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new MyPrefixedRequestMappingHandlerMapping();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.