spring aop处理

spring boot环境(配置按aop1)

实体

public class Article {

    private  String title;
    private  Date posted;
    private  String content;
    private  Integer clicked;

controller:

@RestController
public class CustomerController {
    @RequestMapping("/hello")
    @UserAccess(desc = "注解")
    public Article index() {
        System.out.println("helllo123");

        Article a = new Article();

        a.setTitle("title1");
        Long d=new Date().getTime();

        a.setPosted(new Date(d-100000000L));

        return a;
    }
}

一、普通注解,Date转String,并多种类型

@Aspect
@Component
public class ControllerLog1 {

    @Pointcut("execution(public * com.example.demo1st.*.*(..))")
    public void webLog(){}

    //@Before("execution(public * com.example.demo1st.*.*(..))")
    @Before("webLog()")
    public void startTimee(JoinPoint joinPoint) throws Throwable {

        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        System.out.println("URL : " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD : " + request.getMethod());
        System.out.println("IP : " + request.getRemoteAddr());
        System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));

        //System.out.println("计时开始~~~~~");
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        System.out.println("方法的返回值 : " + ret);
        Object _obj = ret;
        Class<?> resultClz = _obj.getClass();
        Field[] fieldInfo = resultClz.getDeclaredFields(); //获取class里的所有字段  父类字段获取不到    注:如果出现加密解密失败 请先查看idno是否在父类中
        Date posted=null;
        for (Field field : fieldInfo) {
            field.setAccessible(true);

            System.out.println(field.getName()+":---:"+field.get(_obj)+","+field.getType());
            if(field.getType().equals(Date.class)){
                System.out.println("匹配上了------------->!\n");

                Object value = field.get(_obj);
                posted =(Date)value;
                //field.set(_obj,null);
            }

        }
        for (Field field : fieldInfo){
            if(field.getName().equals("content"))
            {   field.setAccessible(true);
                //String con=new Date().toString();

                Date d=new Date();
                int day = (int) ((d.getTime() - posted.getTime()) / (1000 * 60 * 60 * 24));
                int hour=(int) ((d.getTime() - posted.getTime()) / (1000 * 60 * 60 ));
                int min=(int) ((d.getTime() - posted.getTime()) / (1000 * 60  ));
                int sec=(int) ((d.getTime() - posted.getTime()) / (1000   ));
                String dateStr = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss").format(posted);
                if(day>=7){
                    field.set(_obj,dateStr);
                    continue;
                }

                if(day<7&&day>=1) dateStr=day+"天";
                if(day<1&&hour>1) dateStr=hour+"小时";
                if(hour<1&&min>1) dateStr=min+"分钟";
                if(min<1&&sec>1) dateStr=sec+"秒";
                dateStr=dateStr+"前";
                field.set(_obj,dateStr);
            }
        }

    }

    //后置异常通知
    @AfterThrowing("webLog()")
    public void throwss(JoinPoint jp){
        System.out.println("方法异常时执行.....");
    }

    //后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
    @After("webLog()")
    public void after(JoinPoint jp){
        System.out.println("方法最后执行.....");
    }

    //环绕通知,环绕增强,相当于MethodInterceptor
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        System.out.println("方法环绕start.....");
        try {
            Object o =  pjp.proceed();
            System.out.println("方法环绕proceed,结果是 :" + o);
            return o;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
}

 二、 注解aop

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAccess {
    String desc() default "无信息";
}

  

@Component
//@Aspect
public class UserAccessAspect {

    @Pointcut(value = "@annotation( com.example.demo1st.config.UserAccess)")
    public void access() {

    }

    @Before("access()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        System.out.println("second before");
    }

    @AfterReturning(returning = "ret", pointcut = "@annotation(userAccess)")
    public void doAfterReturning(Object ret, UserAccess userAccess) throws Throwable {

        System.out.println("second ret:" + userAccess.desc());
        System.out.println("注解方法的返回值 : " + ret);
    }

    @Around("@annotation(userAccess)")
    public Object around(ProceedingJoinPoint pjp, UserAccess userAccess) {
        //获取注解里的值
        System.out.println("second around:" + userAccess.desc());

        ProceedingJoinPoint joinPoint=pjp;
        Object target = joinPoint.getTarget().getClass().getName();
        System.out.println("调用者+"+target);
        //通过joinPoint.getArgs()获取Args参数
/*
        Object[] args = joinPoint.getArgs();//2.传参  
        System.out.println("2.传参:----"+args[0]);
        for (Object object : args) {
             System.out.println(object instanceof HttpServletRequest);
        }
*/
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }
}

  

 

 

posted @ 2018-12-04 18:16  cnchengv  阅读(99)  评论(0编辑  收藏  举报