简体   繁体   English

如何基于自定义注释修改RequestMapping值

[英]How to modify RequestMapping value based on custom annotation

I want to write something like (simplified) 我想写类似(简体)的东西

@MyAnnnotationForPrefix("/foo1")
@RestController
@RequestMapping("/bar")
public class Test1Controller{
    ...
}

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

And access them via url /foo1/bar and /foo2/bar urls. 并通过url /foo1/bar/foo2/bar url访问它们。 Where should I place logic for handling @MyAnnnotationForPrefix ? 我应该在哪里放置用于处理@MyAnnnotationForPrefix逻辑?

It seems to be done like this (please correct me if this solution has any drawbacks and I'll happily accept you answer) 似乎是这样完成的(如果此解决方案有任何缺点,请纠正我,我会很乐意接受您的回答)

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()
        );
}

} }

Also you need add this RequestMappingHandlerMapping to you webmvc config. 另外,您需要将此RequestMappingHandlerMapping添加到webmvc配置中。 In spring-boot this is done, defining bean: 在spring-boot中,定义了bean:

@Component
public class MyPrefixedWebMvcRegistrations extends WebMvcRegistrationsAdapter {

    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new MyPrefixedRequestMappingHandlerMapping();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM