这篇文章主要介绍了如何实现spring@aspect注解aop,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
@AspectJ 作为通过 Java 5 注释注释的普通的 Java 类,它指的是声明 aspects 的一种风格。通过在你的基于架构的 XML 配置文件中包含以下元素,@AspectJ 支持是可用的。
第一步:编写切面类
package com.dascom.hawk.app.web.tool;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AnnotationAspectJ {
//定义切面("execution(* com.dascom.common.aop.*.*(..)))
//当前配置的意思是所有添加了SuiteMessage的注解的方法作为切点
@Pointcut("@annotation(com.dascom.common.annotation.SuiteMessage)")
public void logPointCut() {
}
//前置通知
@Before("logPointCut()")
public void before(JoinPoint point) {
String calssName = point.getTarget().getClass().getName();
String method = point.getSignature().getName();
System.out.println(calssName + " : " + method);
}
//后置通知
@After("logPointCut()")
public void after(JoinPoint point) {
String method = point.getSignature().getName();
System.out.println(method + ": end----");
}
//环绕通知
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//异步保存日志
System.out.println(time);
return result;
}
}
第二步:在spring的配置文件中添加注解扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.dascom.hawk.app.web.tool"></context:component-scan>
<!-- 自动为切面方法中匹配的方法所在的类生成代理对象。
proxy-target-class="true" 这个的作用是struts的控制类都基础的actionSupport,必须添加这个,不然会报错
-->
<aop:aspectj-autoproxy proxy-target-class="true" />
</beans>
第三步:搞定。爽歪歪~~~
感谢你能够认真阅读完这篇文章,希望小编分享的“如何实现spring@aspect注解aop”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。