1. 程式人生 > >AOP通過反射獲取自定義註解

AOP通過反射獲取自定義註解

ram tar .get tty sig runt type log eth

自定義註解:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface DemoAnno {
    String value()  default "";
}

AOP:

    @Pointcut("@annotation(com.hephae.aop.aop.DemoAnno)")
    public void demoAspect() {
    }

    @Around(value = "demoAspect()")
    
public Object around(ProceedingJoinPoint joinPoint) throws Throwable { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature)signature; //method為接口的Method對象,獲取不到實現類方法上的註解 Method method = methodSignature.getMethod(); //targetMethod為實現類方法對象
Method targetMethod = joinPoint.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); DemoAnno demoAnno = targetMethod.getAnnotation(DemoAnno.class); if (demoAnno != null) { String value = demoAnno.value(); } Object obj = null
; obj = joinPoint.proceed(); return obj; }

AOP通過反射獲取自定義註解