我有同樣的擔心,是不是春天EL選項的粉絲,由於記錄的問題,我想前綴在控制器上嚴格控制,但我不想依靠開發者做正確的事情。
這幾天可能有更好的方法,但這是我做的。你們能否看到任何缺點,我仍然在測試任何副作用。
- 定義自定義註釋。
這允許開發人員顯式提供類型化屬性,如int apiVersion(),String resourceName()。這些值將在稍後作爲前綴的基礎。
- 這個新的註釋
- 註釋休息控制器實現了自定義RequestMappingHandlerMapping
在RequestMappingHandlerMapping,我可以讀取自定義註解的屬性和修改最終RequestMappingInfo因爲我需要。這裏有一些代碼片段:
@Configuration
public class MyWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
return new MyCustomRequestMappingHandlerMapping();
}
}
而在MyCustomRequestMappingHandlerMapping,覆蓋registerHandlerMethod:
private class MyCustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
private Logger myLogger = LoggerFactory.getLogger(MyCustomRequestMappingHandlerMapping.class);
public MyCustomRequestMappingHandlerMapping() {
super();
}
@Override
protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
// find the class declaring this method
Class<?> beanType = method.getDeclaringClass();
// check for the My rest controller annotation
MyRestController myRestAnnotation = beanType.getAnnotation(MyRestController.class);
if (myRestAnnotation != null) {
// this is a My annotated rest service, lets modify the URL mapping
PatternsRequestCondition oldPattern = mapping.getPatternsCondition();
// create a pattern such as /api/v${apiVersion}/${resourceName}
String urlPattern = String.format("/api/v%d/%s",
myRestAnnotation.apiVersion(),
myRestAnnotation.resourceName());
// create a new condition
PatternsRequestCondition apiPattern =
new PatternsRequestCondition(urlPattern);
// ask our condition to be the core, but import all settinsg from the old
// pattern
PatternsRequestCondition updatedFinalPattern = apiPattern.combine(oldPattern);
myLogger.info("re-writing mapping for {}, myRestAnnotation={}, original={}, final={}",
beanType, myRestAnnotation, oldPattern, updatedFinalPattern);
mapping = new RequestMappingInfo(
mapping.getName(),
updatedFinalPattern,
mapping.getMethodsCondition(),
mapping.getParamsCondition(),
mapping.getHeadersCondition(),
mapping.getConsumesCondition(),
mapping.getProducesCondition(),
mapping.getCustomCondition()
);
}
super.registerHandlerMethod(handler, method, mapping);
}
}
在Jira爲此打開了一張票:https://jira.spring.io/browse/SPR-13882 – pczeus