问题
I'm trying to apply formatter-annotation to the field "phone" in next model-class:
public class User {
@ContactNumberFormate
private String phone;
}
Interface for annotation:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberFormate {
}
Formatter:
@Component
public class PhoneFormatter implements Formatter<String> {
@Override
public String parse(String phoneNum, Locale locale) throws ParseException {
phoneNum = phoneNum.trim();
String regex = "^\\(?(\\+*1)?[-.\\s*]?([0-9]{3})\\)?[-.\\s*]?([0-9]{3})[-.\\s*]?([0-9]{4})$";
Pattern.compile(regex).matcher(phoneNum);
return phoneNum;
}
@Override
public String print(String phone, Locale locale) {
return phone;
}
}
Annotation-factory:
public class PhoneFormatAnnotationFormatterFactory implements
AnnotationFormatterFactory<ContactNumberFormate> {
@Override
public Set<Class<?>> getFieldTypes() {
return Collections.singleton(String.class);
}
@Override
public Printer<?> getPrinter(ContactNumberFormate contactNumberFormate, Class<?> aClass) {
return new PhoneFormatter();
}
@Override
public Parser<?> getParser(ContactNumberFormate contactNumberFormate, Class<?> aClass) {
return new PhoneFormatter();
}
}
FormatterRegistrar:
public class ApplicationFormatterRegister implements FormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry formatterRegistry) {
formatterRegistry.addFormatterForFieldAnnotation(new PhoneFormatAnnotationFormatterFactory());
}
}
config:
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="applicationConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars">
<set>
<ref bean="applicationFormatterRegistrar"/>
</set>
</property>
</bean>
<bean id="applicationFormatterRegistrar" class="ru.spb.dreamwhite.util.phoneUtil.ApplicationFormatterRegister"/>
And it does not work: phone-values saved in database, but in non-formatted form.
Note: when I run test in debug with breakpoint on PhoneFormatter, test passes susseccfully. That means, that my Formatter is out of process. But when I set breakpoint on PhoneFormatAnnotationFormatterFactory.getFieldTypes
, test interrupted.
In particular, debug with breakpoint on return Collections.singleton(String.class);
in
public Set<Class<?>> getFieldTypes() {
return Collections.singleton(String.class);
}
shows that the class PhoneFormatAnnotationFormatterFactory
has no fields...
来源:https://stackoverflow.com/questions/60263162/spring-custom-formatter-to-field-annotation-does-not-work