Как изменить значение RequestMapping на основе пользовательской аннотации

Я хочу написать что-то вроде (упрощенно)

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

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

И получить к ним доступ через URL /foo1/bar а также /foo2/bar URLs. Где я должен разместить логику для обработки @MyAnnnotationForPrefix?

1 ответ

Похоже, что это сделано так (пожалуйста, исправьте меня, если у этого решения есть какие-либо недостатки, и я с радостью приму ваш ответ)

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. В весенней загрузке это делается, определяя bean-компонент:

@Component
public class MyPrefixedWebMvcRegistrations extends WebMvcRegistrationsAdapter {

    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new MyPrefixedRequestMappingHandlerMapping();
    }
}
Другие вопросы по тегам