首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据自定义注解修改RequestMapping值

如何根据自定义注解修改RequestMapping值
EN

Stack Overflow用户
提问于 2018-06-19 19:08:43
回答 1查看 461关注 0票数 0

我想写一些像这样的东西(简化)

代码语言:javascript
复制
@MyAnnnotationForPrefix("/foo1")
@RestController
@RequestMapping("/bar")
public class Test1Controller{
    ...
}

@MyAnnnotationForPrefix("/foo2")
@RestController
@RequestMapping("/bar")
public class Test2Controller{
    ...
}

并通过url /foo1/bar/foo2/bar url访问它们。我应该把处理@MyAnnnotationForPrefix的逻辑放在哪里?

EN

回答 1

Stack Overflow用户

发布于 2018-06-19 20:26:36

它似乎是这样做的(如果这个解决方案有任何缺点,请纠正我,我很乐意接受你的答案)

代码语言:javascript
复制
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完成的:

代码语言:javascript
复制
@Component
public class MyPrefixedWebMvcRegistrations extends WebMvcRegistrationsAdapter {

    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new MyPrefixedRequestMappingHandlerMapping();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50926952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档