springboot 自定义格式化器(Formatter)
应用:自定义格式化注解解析字符串
***********************
相关类与接口
Formatter
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
Parser:解析指定格式的字符串,转换为对象T
@FunctionalInterface
public interface Parser<T> {
T parse(String text, Locale locale) throws ParseException;
}
Printer:转换后的对象T输出为字符串
@FunctionalInterface
public interface Printer<T> {
String print(T object, Locale locale);
}
AnnotationFormatterFactory
public interface AnnotationFormatterFactory<A extends Annotation> {
Set<Class<?>> getFieldTypes(); //注解可以标注的字段类型
Printer<?> getPrinter(A annotation, Class<?> fieldType);
Parser<?> getParser(A annotation, Class<?> fieldType);
}
***********************
示例
*****************
formatter 层
BooleanFormat
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER})
public @interface BooleanFormat {
}
BooleanFormatter
@Component
public class BooleanFormatter implements Formatter<Boolean> {
private final String[] values={"是","1","ok","true"};
@Override
public Boolean parse(String text, Locale locale) throws ParseException {
return Arrays.asList(values).contains(text.toLowerCase());
}
@Override
public String print(Boolean object, Locale locale) {
return object?"true":"false";
}
}
CustomBooleanFormatAnnotationFactory
@Component
public class CustomBooleanFormatAnnotationFactory implements AnnotationFormatterFactory<BooleanFormat> {
@Resource
private BooleanFormatter booleanFormatter;
@Override
public Set<Class<?>> getFieldTypes() {
Set<Class<?>> set=new HashSet<>();
set.add(Boolean.class);
return set;
}
@Override
public Parser<?> getParser(BooleanFormat annotation, Class<?> fieldType) {
return booleanFormatter;
}
@Override
public Printer<?> getPrinter(BooleanFormat annotation, Class<?> fieldType) {
return booleanFormatter;
}
}
*****************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(@BooleanFormat Boolean value){
System.out.println(value);
return value.toString();
}
}
***********************
使用测试
localhost:8080/hello?value=ok
2020-07-12 10:56:50.812 INFO 5376 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-12 10:56:50.823 INFO 5376 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 11 ms
true
localhost:8080/hello?value=是
true