自定义注解

自定义注解 @Vertify注解,@NotNull注解,@Length注解,@Valid注解,拦截@Vertify注解修饰的方法,对方法中参数使用@Valid的数据进行数据校验,如果对象中属性存在@NotNull注解修饰的属性,则该属性必须不能为null;@Length注解修饰的属性,长度必须满足要求,否则抛出异常“必填项不能为空”/“字段长度不满足要求”

自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Vertify {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Valid {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotNull {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Length {
    int min() default 3;
    int max() default 6;
}

实体类

package com.igeek.pojo;

import com.igeek.annotation.Length;
import com.igeek.annotation.NotNull;

public class Account {

    @NotNull
    private Long no;
    @Length(min = 2,max = 10)
    private String username;
    private String password;
    private Double money;

    public Long getNo() {
        return no;
    }

    public void setNo(Long no) {
        this.no = no;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public Account(Long no, String username, String password, Double money) {
        this.no = no;
        this.username = username;
        this.password = password;
        this.money = money;
    }

    public Account() {
    }

    @Override
    public String toString() {
        return "Account{" +
                "no=" + no +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", money=" + money +
                '}';
    }
}

service
IAccountService

void update(@Valid Account account);

AccountServiceImpl

@Override
    @Vertify
    public void update(@Valid Account account) {
        accountDao.update(account);
    }

切面类

package com.igeek.aspect;

import com.igeek.annotation.Length;
import com.igeek.annotation.NotNull;
import com.igeek.annotation.Valid;
import org.aopalliance.intercept.Joinpoint;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Component
@Aspect
public class MyAspect {

    @Pointcut("execution(* com.igeek.service..*.*(..))")
    private void mypt(){}

    @Pointcut("@annotation(com.igeek.annotation.Vertify)")
    private void mypt2(){}

    private Logger logger = Logger.getLogger(MyAspect.class);

    @AfterThrowing(value = "mypt()",throwing = "ex")
    public void writeLog(Exception ex){
        logger.error(ex.getMessage());
    }

    @Before(value = "mypt2()")
    public void vertify(JoinPoint jp) {
        //获取方法的参数(实参)
        Object[] args = jp.getArgs();
        //通过连接点获取方法
        MethodSignature methodSignature = (MethodSignature)jp.getSignature();
        //获取拦截的方法
        Method method = methodSignature.getMethod();
        //获取拦截的方法的所有参数(形参)
        Parameter[] parameters = method.getParameters();

        for (int i = 0; i< parameters.length; i++) {
            Parameter parameter = parameters[i];
            //如果参数上有@Valid注解
            if (parameter.getAnnotation(Valid.class) != null) {
                //实际参数
                Object obj = args[i];
                //判断实际参数对象的属性是否满足注解要求
                //获取对象所属的类的所有属性
                Field[] declaredFields = obj.getClass().getDeclaredFields();

                for (Field field : declaredFields) {
                    field.setAccessible(true);//设置可见性
                    //包含注解
                    if (field.isAnnotationPresent(NotNull.class)) {
                        //获取对象中的该属性 判断是否为null
                        try {
                            Object o = field.get(obj);
                            if (o == null) {
                                throw new RuntimeException("必填字段为空!");
                            }
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                    } else if (field.isAnnotationPresent(Length.class)) {
                        //获取字段上属性的值
                        Length annotation = field.getAnnotation(Length.class);
                        try {
                            String o = (String)field.get(obj);
                            if (o == null || o.length() < annotation.min() || o.length() > annotation.max()) {
                                throw new RuntimeException("长度不符合要求");
                            }
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

测试类AppTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AppTest {

    //private Logger logger = Logger.getLogger(AppTest.class);

    @Autowired
    private IAccoutService accoutService;

    @Test
    public void test02(){
        Account account = new Account(1L,"1231245654678","123456789",1500.0);
        accoutService.update(account);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值