spring-aop自定义注解需要了解自定义注解有需求的可以看我的自定义注解
博客地址:自定义注解
需求:我这有个短信服务,需要知道发送的内容和发送人还有发送状态是否成功
话不多说上代码
创建自定义注解
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SendMessgeAnnotate {
/**
* 可以给注解加上值不同的方法上注解可以设置不同的值为了功能区分
*/
String messgeType() default "";
}
创建切面类
public class LogAspect {
@Autowired
private MessageTemplateService messageTemplateService;
@Autowired
private MessageLogService messageLogService;
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**/
@Pointcut("@annotation(com.zghfws.alarmserver.log.SendMessgeAnnotate)")
public void messagepointCut(){};
@AfterReturning(value = "messagepointCut() && @annotation(messgeAnnotate)",returning = "obj")
public void savemessage(JoinPoint joinPoint, SendMessgeAnnotate messgeAnnotate,Boolean obj){
//获取所有连接点的参数
Object[] args = joinPoint.getArgs();
if(args!=null&&args.length>0&&obj==true){
//获得模板详情
MessageLog messageLog = new MessageLog();
MessageTemplate messageTemplate=null;
if(args[1] instanceof String){
messageTemplate = messageTemplateService.getById((String) args[1]);
if(args.length==2){
if(args[0] instanceof String)
messageLog.setPhoneNumber((String) args[0]);
messageLog.setTemplateCode((String) args[1]);
if(messageTemplate!=null){
messageLog.setSenddetail(messageTemplate.getTemplateDeatil());
}
}else if(args.length==3){
if(args[0] instanceof String)
messageLog.setPhoneNumber((String) args[0]);
messageLog.setTemplateCode((String) args[1]);
if(messageTemplate!=null){
messageLog.setSenddetail(messageTemplate.getTemplateDeatil());
}
messageLog.setSendparams(JSON.toJSONString(args[2]));
}
messageLogService.save(messageLog);
}
}
}
}
连接点(方法上加入注解)
@Override
@SendMessgeAnnotate
public Boolean sendMessge(String phone, String templateCode) {
boolean b = msgUtill.SendMsg(phone, templateCode, null);
return b;
}
解释:
1.切点@pointCut(连接点的集合)这里用的时注解不同于execution()直接用@annotation(注解的全类名) 所有的用上这个注解的join point(连接点)都归属到切点里面
2 @AfterReturning(value = "messagepointCut() && @annotation(messgeAnnotate)",returning = "obj")
value:切入点表达式这里不同于execution(),需要我们切点加上我们自定义的注解表示我们要增强的目标
returning="";返回的joinPoint返回的值
注意:这个JoinPoint导的包是
import org.aspectj.lang.JoinPoint;
不是
import org.aopalliance.intercept.Joinpoint;
import org.aopalliance.intercept.Joinpoint;是基于pojo(xml方式实现的aop代理),想了解额可以自己去看源码,小弟我才疏学浅看的也一知半解,
import org.aspectj.lang.JoinPoint;是基于ASpectj实现的aop,(当前注解驱动的流行时代)