Java Aspect-Oriented Programming with Annotations

后端 未结 5 1643
無奈伤痛
無奈伤痛 2020-11-30 16:57

In a post entitled \"AOP Fundamentals\", I asked for a King\'s English explanation of what AOP is, and what it does. I received some very helpful answers and links

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 17:49

    Here's my contribution to this very useful post.

    We will take a very simple example: we need to take action on some methods' processing. They are annotated with custom annotations, which contain data to handle. Given this data we want to raise an exception or let the process continue like the method was not annotated.

    The Java code for defining our aspect:

    package com.example;
    
    public class AccessDeniedForCustomAnnotatedMethodsAspect {
    
    public Object checkAuthorizedAccess(ProceedingJoinPoint proceedingJointPoint)
    throws Throwable {
    
        final MethodSignature methodSignature = (MethodSignature) proceedingJointPoint
                                                .getSignature();
    
        // how to get the method name
        final String methodName = methodSignature
                                                .getMethod()
                                                .getName();
    
        // how to get the parameter types
        final Class[] parameterTypes = methodSignature
                                                .getMethod()
                                                .getParameterTypes();
    
        // how to get the annotations setted on the method
        Annotation[] declaredAnnotations = proceedingJointPoint
                                                .getTarget()
                                                .getClass()
                                                .getMethod(methodName, parameterTypes)
                                                .getDeclaredAnnotations();
    
        if (declaredAnnotations.length > 0) {
    
            for (Annotation declaredAnnotation : Arrays.asList(declaredAnnotations)) {
    
                // I just want to deal with the one that interests me
                if(declaredAnnotation instanceof CustomAnnotation) {
    
                    // how to get the value contained in this annotation 
                    (CustomAnnotation) declaredAnnotation).value()
    
                    if(test not OK) {
                        throw new YourException("your exception message");
                    }
    
                    // triggers the rest of the method process
                    return proceedingJointPoint.proceed();
               }
            }
        }
    }
    

    The xml configuration :

    
        
            
        
    
    
    
    

    Hope it helps !

提交回复
热议问题