当前位置: 移动技术网 > IT编程>开发语言>Java > Spring MVC通过添加自定义注解格式化数据的方法

Spring MVC通过添加自定义注解格式化数据的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

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);
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网