Spring 自定义注解案例

1. 自定义时间格式注解
@Target(ElementType.FIELD)//作用于字段上
@Retention(RetentionPolicy.RUNTIME)//保留到运行期
public @interface DateParse {

    String format() default "yyyy-MM-dd HH:mm:ss";
}
2. 自定义数据字典注解
@Target(ElementType.FIELD)//作用于字段上
@Retention(RetentionPolicy.RUNTIME)//保留到运行期
public @interface DictParse {

    String dictKey() default "none";
}
3. 定义转换方法
public static <T> T po2Vo(Object fromObj,Class<T> toCla) throws IllegalArgumentException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException{
        Object toObj = toCla.newInstance();
        Field[] toFields = toCla.getDeclaredFields();  

        for(int i = 0 ; i < toFields.length; i++){  
            Field f = toFields[i];  
            f.setAccessible(true); //设置些属性是可以访问的  
            String fieldName = f.getName();
            Object fromVal = getValByFieldName(fromObj, fieldName);
            if(fromVal != null){
                if(f.isAnnotationPresent(DateParse.class)){//处理日期格式的数据
                    Date sDate = (Date)fromVal;
                    DateParse dataParse = f.getAnnotation(DateParse.class);
                    String format = dataParse.format();
                    if(!StringUtil.isEmpty(format)){
                        f.set(toObj, TimeUtil.getDateString(sDate,format));
                    }else{
                        f.set(toObj, TimeUtil.getDateTimeString(sDate));
                    }
                }else{
                    String val = fromVal.toString();
                    f.set(toObj, val);
                    if(f.isAnnotationPresent(DictParse.class)){//处理字典项
                        DictParse dictParse = f.getAnnotation(DictParse.class);
                        String dictKey = dictParse.dictKey();
                        String dictText = RedisReloadUtil.getDictTextByParam(dictKey, val);
                        if(!StringUtil.isEmpty(dictText)){
                            PropertyDescriptor pd = new PropertyDescriptor(f.getName()+"Name", toCla);
                            Method wM = pd.getWriteMethod();//获得写方法
                            wM.invoke(toObj, dictText);
                        }
                    }
                }
            }
        }
        return (T) toObj;
    }
4. 使用(在Vo中定义)
@DateParse(format = "yyyy-MM-dd")
private String createTime;
...get ... set ...
@DictParse(dictKey = "MEMBER_LEVEL")
private String level;
...get ... set ...
private String levelName;
...get ... set ...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值