我想写一些像这样的东西(简化)
@MyAnnnotationForPrefix("/foo1")
@RestController
@RequestMapping("/bar")
public class Test1Controller{
...
}
@MyAnnnotationForPrefix("/foo2")
@RestController
@RequestMapping("/bar")
public class Test2Controller{
...
}并通过url /foo1/bar和/foo2/bar url访问它们。我应该把处理@MyAnnnotationForPrefix的逻辑放在哪里?
发布于 2018-06-19 20:26:36
它似乎是这样做的(如果这个解决方案有任何缺点,请纠正我,我很乐意接受你的答案)
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();
}
}https://stackoverflow.com/questions/50926952
复制相似问题