spring通过注解的方式实现四大通知,只能用前置和后置,如果使用最终通知,该最终通知会在后置或者异常通知之前执行,spring现存问题,所以只演示spring通过注解方式全自动实现环绕通知。
1、引入依赖:
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!--spring aop + aspectj-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
2、配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--自动装配文件位置设置-->
<context:component-scan base-package="com.ljs"/>
<!--配置为自动代理-->
<aop:aspectj-autoproxy/>
</beans>
3、接口
4、接口实现类,注意加组件注解,交给ioc管理。
5、切面类(需要指定为切面类:@Aspect。同时交由ioc管理:@Component)
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Around(value = "execution(* com.ljs.demo.*.*(..))")
public Object around(ProceedingJoinPoint p) throws Throwable {
System.out.println("执行方法前");
for (Object arg : p.getArgs()) {
System.out.println("参数:" + arg);
}
Object proceed = p.proceed(); //推进执行方法
System.out.println("方法返回数据-> "+proceed.toString());
System.out.println("执行方法后");
return proceed;
}
}
6、测试结果,这里一定注意,获取被代理对象,一定要用接口获取,否则会报错。
先记录错误写法:
报错信息:(类型转换异常)
java.lang.ClassCastException: com.sun.proxy.$Proxy19 cannot be cast to com.ljs.demo.DannyEat
正确写法:
7、控制台输出结果