Use of custom annotations

1. Define an annotation,

2. Define an aspect scan to intercept and scan this annotation---the definition of aspect can use annotation @Aspect, or configuration, aspect can scan annotation, including road strength

4, point.proceed(); is the pointcut - the method where the annotation is located, executed in the aspect (so that the target method is executed in the aspect notification)

3. Used in other places (write it on the business method that needs to be monitored (every method needs to be written) (@ExceptionHandler does not need to be written on the target method, but on the notification processing method - does not need to be written on the monitoring method) superior))

 

If you customize the annotation to handle the exception of the method, this time the method will be executed together with the advice in the aspect every time it is executed, and then use the way of handling the exception in the notification, no exception will not be executed,

If there is an exception, catch it and process it according to the logic in the notification

 

/**
 * 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");
        //annotation parameter
        System.out.println("Annotation parameter: "+ errorExecption.code());
        // Currently intercepted classes and methods:
        Class clazz = point.getTarget().getClass();
        Method method = ((MethodSignature) point.getSignature()).getMethod();

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

        // method returns result
        Object result = null;
        Object args = Arrays.asList(point.getArgs());
        try {
            //Execute the method (you can add pre and post notifications before and after the method)
            result = point.proceed();
            //check result
            result = validateResult(result);
        } catch (Throwable e) {
            // record log
            System.out.println(codeName + "() method exception: " + e);
            //print stack info
            e.printStackTrace ();
            // set return information
            result = "Result: An exception was thrown...-------------"+e.getMessage()+", reason: "+e. getCause();
        }
        // return notification
        return result;

    }

    /**
     * After the method is executed
     * @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;
    }
    /**
     * After the method is executed
     * @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
Annotation parameter: 100
query param---->_Test_test
---test---
_Test_test() method exception: java.lang.ArithmeticException: / by zero
---->afterReturning
The method test return with Result: An exception was thrown. . -----------------------/ by zero, reason: null
=========>Result: An exception was thrown. . -----------------------/ by zero, reason: 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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326013278&siteId=291194637