I would like to write custom annotations, that would modify Spring request or path parameters according to annotations. For example instead of this code:
@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") String text) {
text = text.toUpperCase();
System.out.println(text);
return "form";
}
I could make annotation @UpperCase :
@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") @UpperCase String text) {
System.out.println(text);
return "form";
}
Is it possible and if it is, how could I do it ?
As the guys said in the comments, you can easily write your annotation driven custom resolver. Four easy steps,
- Create an annotation e.g.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
String value();
}
- Write a resolver e.g.
public class UpperCaseResolver implements HandlerMethodArgumentResolver {
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(UpperCase.class) != null;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
UpperCase attr = parameter.getParameterAnnotation(UpperCase.class);
return webRequest.getParameter(attr.value()).toUpperCase();
}
}
- register a resolver
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="your.package.UpperCaseResolver"></bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>
or the java config
@Configuration
@EnableWebMvc
public class Config extends WebMvcConfigurerAdapter {
...
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new UpperCaseResolver());
}
...
}
- use an annotation in your controller method e.g.
public String test(@UpperCase("foo") String foo)