Spring MVC通过添加自定义注解格式化数据的方法
springmvc 自定义注解 以及自定义注解的解析
一、自定义注解名字
@Target({ElementType.TYPE, ElementType.METHOD}) //类名或方法上
@Retention(RetentionPolicy.RUNTIME)//运行时
@component//自定义多个注解,且在一个类中添加两个或以上的,只需要加一个 否则会实例化多次。
public @interface SocketMapping {
String value() default "";//参数
}
二、测试类
@SocketMapping("/a")
public class TestAnno {
@SocketMapping(value="/b")
public void ss(){
System.out.println(11);
}
}
三、解析测试类所在的包,反射
ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver();
Resource[] res = rpr.getResources("classpath*:websocket/**.class");//测试类的包
for(int i=0;i<res.length;i++){
String className = res[i].getURL().getPath();
className = className.split("(classes/)|(!/)")[1];
className = className.replace("/", ".").replace(".class", "");//获取到文件结构 com.xl.joe.testAnno
Class<?> cla = Class.forName(className);//获取到文件类
if(cla.isAnnotationPresent(SocketMapping.class)){//判断是否存在自定义注解
System.out.println(cla.getAnnotation(SocketMapping.class).value());//获取自定义注解的属性值
}
Object o = SpringContextUtil.getBean("testAnno");//获取类对象
Method[] methods = cla.getMethods();//获取类的方法
for(Method method:methods){
if(method.isAnnotationPresent(SocketMapping.class)){//找到自定义注解
method.invoke(o, new Object[]{});//反射改方法
}
}
}
遇到一个问题
接口传入开始时间、结束时间,格式为yyyyMMdd,要求查询的数据必须用给定的时间段进行过滤。
比如
http://127.0.0.1:8095/iportal-dev/v1/sms/sending/list?stime=20161001&etime=20161130
但是服务端接受时间后,按照业务要求,应该格式为
20161001 00:00:00< 时间段 <20161130 23:59:59
stime可以使用springMVC默认提供的@DateTimeFormat(pattern = "yyyyMMdd")可以得到正确的开始时间,但是结束时间,默认的格式注解就不能完成需求了~
仿照@DateTimeFormat自定义接口
因为是仿照的,有些可以用的方法就继承下来了,并不需要大改。
@MyDateTimeFormat注解
package cn.jpush.iportal.common.support;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import java.lang.annotation.*;
/**
* 使用方法与@DateTimeFormat一致,但是通过它进行注解的字段,会格式化为当天的23:59:59.
* 其他格式的用法也可以支持.
* @author Administrator
*
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface MyDateTimeFormat {
String style() default "SS";
ISO iso() default ISO.NONE;
String pattern() default "";
}
@MyDateTimeFormat注解处理类
package cn.jpush.iportal.common.support;
import org.springframework.context.support.EmbeddedValueResolutionSupport;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
import java.util.*;
public class MyDataTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory<MyDateTimeFormat> {
private static final Set<Class<?>> FIELD_TYPES;
static {
Set<Class<?>> fieldTypes = new HashSet<Class<?>>(4);
fieldTypes.add(Date.class);
fieldTypes.add(Calendar.class);
fieldTypes.add(Long.class);
FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
}
@Override
public Set<Class<?>> getFieldTypes() {
return FIELD_TYPES;
}
@Override
public Printer<?> getPrinter(MyDateTimeFormat annotation, Class<?> fieldType) {
return getFormatter(annotation, fieldType);
}
@Override
public Parser<?> getParser(MyDateTimeFormat annotation, Class<?> fieldType) {
return getFormatter(annotation, fieldType);
}
protected Formatter<Date> getFormatter(MyDateTimeFormat annotation, Class<?> fieldType) {
MyDateFormatter formatter = new MyDateFormatter();
formatter.setStylePattern(resolveEmbeddedValue(annotation.style()));
formatter.setIso(annotation.iso());
formatter.setPattern(resolveEmbeddedValue(annotation.pattern()));
return formatter;
}
}
重载parse接口
通过调用原来的处理函数super.parse(text, locale) ,得到转化的Date对象,然后再添加相关的处理业务,然后返回Date。
package cn.jpush.iportal.common.support;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.datetime.DateFormatter;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class MyDateFormatter extends DateFormatter {
@Override
public Date parse(String text, Locale locale) throws ParseException {
Date target = super.parse(text, locale);
//+1天
Date date = DateUtils.ceiling(new Date(target.getTime() + 1), Calendar.DATE);
//减1ms,得出23:59:59
Date result =new Date(date.getTime()-1);
return result;
}
}
向SpringMVC注册我们的自定义注解处理类
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addFormatters(FormatterRegistry registry) {
MyDataTimeFormatAnnotationFormatterFactory annoFormater =new MyDataTimeFormatAnnotationFormatterFactory();
registry.addFormatterForFieldAnnotation(annoFormater);
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
相关文章
Intellj Idea中的maven工程Java文件颜色不对,未被识别的解决
这篇文章主要介绍了Intellj Idea中的maven工程Java文件颜色不对,未被识别的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08
maven安装、使用、配置本地仓库、idea配置maven以及解决plugins报错问题
本地仓库是远程仓库的一个缓冲和子集,当你构建Maven项目时首先会从本地仓库查找资源,如果没有那么Maven会从远程仓库下载到你本地仓库,这篇文章主要给大家介绍了关于maven安装、使用、配置本地仓库、idea配置maven以及解决plugins报错问题的相关资料,需要的朋友可以参考下2024-01-01
Java技能点之SimpleDateFormat进行日期格式化问题
这篇文章主要介绍了Java技能点之SimpleDateFormat进行日期格式化问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-04-04


最新评论