How to modify RequestMapping value based on custom annotation

时间:2018-06-19 11:08:43

标签: java spring spring-mvc

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. Where should I place logic for handling @MyAnnnotationForPrefix?

1 个答案:

答案 0 :(得分:0)

似乎是这样完成的(如果此解决方案有任何缺点,请纠正我,我会很乐意接受您的回答)

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