> 文章列表 > 实用-AOP切入方法执行

实用-AOP切入方法执行

实用-AOP切入方法执行

目录

1.描述

2.代码

2.1自定义注解

2.2注解执行切面

2.3注解使用

2.4打印结果

3.总结


1.描述

用springaop切入一个方法,做一些业务。

代用自定义注解形式,可以自定义指定注解属性含义。

2.代码

2.1自定义注解

package vip.mate.marketing.config.aop;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 自定义注解 MessageAuto,用来标注自动发送通知消息的地方** @author zhangpan* @date 2023-04-03 09:15:13*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MessageAuto {String type() default ""; //业务类型String value() default ""; //值
}

2.2注解执行切面

其中,publishVO是个实体类

package vip.mate.marketing.config.aop;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import vip.mate.marketing.paramvo.PublishVo;import java.lang.reflect.Method;/*** MessageAutoAspect,自定义注解执行* 万能小切入** @author alspd* @date 2023-04-03 09:15:13*/
@Aspect
@Component
@Slf4j
public class MessageAutoAspect {@Pointcut("@annotation(MessageAuto)")public void operatePointCut() {}@Around("operatePointCut()")public boolean pushMessage(ProceedingJoinPoint point) throws Throwable {Object[] args = point.getArgs();log.info("args:{}", args);MethodSignature signature = (MethodSignature) point.getSignature();Method method = signature.getMethod();MessageAuto messageAuto = method.getAnnotation(MessageAuto.class);String value = messageAuto.value();String type = messageAuto.type();log.info("type:{},value:{}", type, value);//消息入库if ("publish".equalsIgnoreCase(type)) {PublishVo publishVo = (PublishVo) args[0];Long userId = (Long) args[1];log.info("publishVo:{}", publishVo);log.info("userId:{}", userId);}point.proceed();return true;}}

2.3注解使用

 

2.4打印结果

 

3.总结

这就是aop简单使用,业务部分,可自由扩展。