自定义注解的使用

1,定义一个注解,

2,定义一个切面扫拦截描这个注解即可---切面的定义可以用注解@Aspect,也可以用配置,切面可以扫描注解,包路劲

4,point.proceed();就是切点--注解所在的方法,在切面中执行(这样把目标方法放在切面通知中执行)

3,其他的地方用(写到需要监控的业务方法上(每个方法都需要写)(@ExceptionHandler不需要写在目标方法上,而是写在通知处理方法上--不需要写在监控方法上))

 

如果自定义注解来处理方法的异常,这回这个方法每次执行都会放在切面中的通知一起执行,然后用通知中处理异常的方式,没有异常不执行,

有异常就catch到按照通知中的逻辑处理

 

/**
 * ErrorCode:
 *
 * @author yangzhenlong
 * @since 2016/7/21
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ErrorException {
    int code() default 0;//参数
}







/**
 * ErrorExceptionAspect:
 *
 * @author yangzhenlong
 * @since 2016/7/21
 */
@Component
@Aspect
public class ErrorExceptionAspect {

    //@Before("execution(* com.sarkuya.service..*.*(..))")
    @Pointcut(value = "@annotation(com.mlxs.mvc.anno.ErrorException)")
    private void pointcut() {
    }

    @Around(value = "pointcut() && @annotation(errorExecption)")
    public Object around(ProceedingJoinPoint point, ErrorException errorExecption){
        System.out.println("---->around");
        //注解参数
        System.out.println("注解参数:"+ errorExecption.code());
        //当前拦截的类和方法:
        Class clazz = point.getTarget().getClass();
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        String codeName = clazz.getSimpleName()+"_"+method.getName();
        System.out.println("query param---->"+codeName);

        //方法返回结果
        Object result = null;
        Object args = Arrays.asList(point.getArgs());
        try {
            //执行方法(可以在方法前后添加前置和后置通知)
            result = point.proceed();
            //校验结果
            result = validateResult(result);
        } catch (Throwable e) {
            //记录日志
            System.out.println(codeName + "()方法异常:" + e);
            //打印堆栈信息
            e.printStackTrace();
            //设置返回信息
            result = "结果:抛了异常了。。-----------------------"+e.getMessage()+",原因:"+e.getCause();
        }
        //返回通知
        return result;

    }

    /**
     * 方法执行后
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "pointcut() && @annotation(errorExecption)", returning = "result")
    public Object afterReturning(JoinPoint joinPoint, ErrorException errorExecption,  Object result){
        System.out.println("---->afterReturning");
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " return with " + result);
        if(result instanceof Boolean){
            if(!((Boolean) result)){
                result = "error----result is false";
            }
        }else{
            if(result == null){
                result = "error----result is null";
            }
        }
        return result;
    }
    /**
     * 方法执行后
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value = "pointcut() && @annotation(errorExecption)", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, ErrorException errorExecption, Exception ex){
        System.out.println("eeeee--->afterThrowing");
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + "occurs exception: " + ex);
    }

    private Object validateResult(Object result){
        if(result instanceof Boolean){
            if(!((Boolean) result)){
                System.out.println("error----result is false");
                result = "error:false";
            }
        }else{
            if(result == null){
                System.out.println("error----result is null");
                result = "error:null";
            }
        }
        return result;
    }
}




/**
 * _Test:
 *
 * @author yangzhenlong
 * @since 2016/7/21
 */
@Component("test")
public class _Test {

    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("classpath*:spring/applicationContext.xml");
        _Test obj = (_Test) context.getBean("test");
        System.out.println("==========>"+obj.test());
        //System.out.println("==========>"+obj.test2());
    }

    @ErrorException(code = 100)
    public Object test(){
        System.out.println("---test---");
        int a = 10/0;
        return 20;
    }

    @ErrorException(code = 22)
    public Object test2(){
        System.out.println("---test2---");
        //int a = 10/0;
        return false;
    }

}





---->around
注解参数:100
query param---->_Test_test
---test---
_Test_test()方法异常:java.lang.ArithmeticException: / by zero
---->afterReturning
The method test return with 结果:抛了异常了。。-----------------------/ by zero,原因:null
==========>结果:抛了异常了。。-----------------------/ by zero,原因:null
java.lang.ArithmeticException: / by zero
    at com.mlxs.mvc.anno._Test.test(_Test.java:28)
    at com.mlxs.mvc.anno._Test$$FastClassBySpringCGLIB$$cc5ae48c.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.mlxs.mvc.anno.ErrorExceptionAspect.around(ErrorExceptionAspect.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    at com.mlxs.mvc.anno._Test$$EnhancerBySpringCGLIB$$cbf2effd.test(<generated>)
    at com.mlxs.mvc.anno._Test.main(_Test.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

猜你喜欢

转载自yuhuiblog6338999322098842.iteye.com/blog/2415459