基于AOP的自定义注解简单实现

时间:2021-07-02 20:41:40

1、配置spring bean

<bean id="logAspect" class="com.ksource.core.aop.LogAspect"/>

2、配置一个aop

<aop:config proxy-target-class="true">
<aop:aspect ref="logAspect" > //对应的bean 切点处理逻辑
<aop:pointcut expression="execution(* com.ksource.platform.controller..*.*(..)) || execution(* com.ksource.brdge.controller..*.*(..)) || execution(* com.ksource.otter.manager.controller..*.*(..))" id="logPointcut"/> //切点作用范围
<aop:around pointcut-ref="logPointcut" method="doAudit"/> //切点具体处理方法
</aop:aspect>
</aop:config>

3、切点处理逻辑

public Object doAudit(ProceedingJoinPoint point) throws Throwable {
String methodName = point.getSignature().getName(); //切点的方法
Class targetClass = point.getTarget().getClass(); //切点的类

Method[] methods = targetClass.getMethods();
Method method = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName() == methodName) {
method = methods[i];
break;
}
}

if (method == null) {
return point.proceed();
}

BigEventAction annotation = (BigEventAction) method.getAnnotation(BigEventAction.class); //自定义注解对象

if (annotation == null) {
return point.proceed();
}
Object returnVal = point.proceed(); //切点执行方法
doBigEvent(annotation); //具体处理逻辑
return returnVal;
}
4、自定义注解接口

@Target({ java.lang.annotation.ElementType.METHOD,
java.lang.annotation.ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface BigEventAction {
public abstract String type() default "";
public abstract String detail() default "";
}

5、注解应用

@BigEventAction(type="添加",detail="日志信息")
public void test(){
}

如有问题请加个人微信,一块探讨学习!

基于AOP的自定义注解简单实现