Я пытаюсь запустить мой Formatter для моей модели. Модель содержит аннотацию, подобную следующему коду. У меня есть несколько Formatter, которые я еще не запускаю, но не могу понять проблему.
public class Customer {
@Trim
private String firstName;
//some other properties, getter and setter
}
Аннотация правильно установлена, насколько я знаю:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface Trim {
boolean squashMultipleSpaces() default true;
}
И завод по производству аннотаций
public class TrimAnnotationFormatterFactory implements AnnotationFormatterFactory<Trim> {
public TrimAnnotationFormatterFactory() {
}
public Set<Class<?>> getFieldTypes() {
return Collections.singleton(String.class);
}
public Printer<String> getPrinter(Trim annotation, Class<?> fieldType) {
return new TrimAnnotationFormatterFactory.TrimFormatter(annotation.squashMultipleSpaces());
}
public Parser<String> getParser(Trim annotation, Class<?> fieldType) {
return new TrimAnnotationFormatterFactory.TrimFormatter(annotation.squashMultipleSpaces());
}
private static class TrimFormatter implements Formatter<String> {
private final boolean squashMultipleSpaces;
TrimFormatter(boolean squashMultipleSpaces) {
this.squashMultipleSpaces = squashMultipleSpaces;
}
public String parse(String text, Locale locale) {
return this.process(text);
}
public String print(String object, Locale locale) {
return this.process(object);
}
private String process(String text) {
if (text == null) {
return null;
} else {
return this.squashMultipleSpaces ? text.trim().replaceAll("\\s+", " ") : text.trim();
}
}
}
}
Я добавил свой собственный AnnotationFormatterFactory в FormatterRegistry. Когда я его копирую, я вижу, что он успешно добавлен в FormatterRegistry.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldAnnotation(new TrimAnnotationFormatterFactory());
}
}
А контроллер выглядит так:
@Controller
public class CustomerController {
@PostMapping(value = "/customer")
@ResponseBody
public Customer saveCustomer(@RequestBody Customer customer) {
return customer;
}
}
если мой ввод выглядит так
" Christian Walter"
в контроллере модель все та же. Я ожидал
"Christian Walter"
в моей модели.
Почему мой форматер не работает? Или я должен использовать PropertyEditor, и если да, то как я могу использовать его с аннотациями?
ОБНОВЛЕНИЕ: форматер успешно зарегистрирован, но не вызывается. И добавил контроллер.
Спасибо за вашу помощь.