1. 实现WebMvcConfigurationSupport中的addArgumentResolvers方法的复写:
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new NameArgumentResolver());
super.addArgumentResolvers(argumentResolvers);
}
}
2. NameArgumentResolver定义如下:
package cn.ok;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.lang.annotation.Annotation;
@Service
public class NameArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(Name.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
Annotation[] methodAnnotations = methodParameter.getParameterAnnotations();
for (Annotation methodAnnotation : methodAnnotations) {
if (methodAnnotation instanceof Name) {
Name localToken = (Name) methodAnnotation;
if ("name".equals(localToken.value())) {
if (String.class.isAssignableFrom(methodParameter.getParameterType())) {
return "welcom to come to hello word";
}
}
}
return null;
}
return "";
}
}
3.自定义枚举Name如下:
package cn.ok;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Name {
String value() default "name";
}
4.Controller接口如下:
@RequestMapping(value = "/optional/name", method = { RequestMethod.GET })
public Object requestName(@Name String name) {
return name;
}
5. 返回结果为:
welcom to come to hello word