Я пытаюсь применить форматер-аннотацию к полю "телефон" в следующем классе моделей:
public class User {
@ContactNumberFormate
private String phone;
}
Интерфейс для аннотации:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberFormate {
}
Форматер:
@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;
}
}
Заводская аннотация:
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"/>
И это не работает: phone- значения сохраняются в базе данных, но в неформатированном виде.
Примечание: когда я запускаю тест в режиме отладки с точкой останова на PhoneFormatter, тест проходит успешно. Это означает, что мой Formatter вне процесса. Но когда я установил точку останова на PhoneFormatAnnotationFormatterFactory.getFieldTypes
, тестирование прервалось.
В частности, отладка с точкой останова на return Collections.singleton(String.class);
в
public Set<Class<?>> getFieldTypes() {
return Collections.singleton(String.class);
}
показывает, что у класса PhoneFormatAnnotationFormatterFactory
нет полей ...