首先加入jar包:
com.springsource.net.sf.cglib -2.2.0.jar
com.springsource.org.aopalliance-1.0.0 .jar
com.springsource.org.aspectj.weaver-1.6.8 .RELEASE.jar
commons-logging-1.1.3. jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE. jar
声明一个接口:
public interface MyMath { public int add(int i,int j); public void sub(int i,int j); public void mul(int i,int j); public void div(int i,int j); }
创建一个类实现接口
@Component public class MyMathImpl implements MyMath{ @Override public int add(int i, int j) { int result=i+j; System.out.println("目标方法add执行了, "+result); return result; } @Override public void sub(int i, int j) { // TODO Auto-generated method stub int result=i-j; System.out.println("目标方法sub执行了, "+result); } @Override public void mul(int i, int j) { // TODO Auto-generated method stub int result=i*j; System.out.println("目标方法mul执行了, "+result); } @Override public void div(int i, int j) { // TODO Auto-generated method stub int result=i/j; System.out.println("目标方法div执行了, "+result); } }
在applicationcontext.xml 中配置扫描包和开启AOP注解
<?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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!--扫描包 --> <context:component-scan base-package="com.neuedu.bean"></context:component-scan> <!-- 开启AOP注解 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
创建环绕通知的切面类
@Component @Aspect public class Txaspect { @Around(value = "execution(public * com.neuedu.bean.MyMathImpl.*(..))") public Object showLog(ProceedingJoinPoint point) { Object[] args = point.getArgs(); Object object = null; try { object=point.proceed(args); } catch (Throwable e1) { // TODO Auto-generated catch block e1.printStackTrace(); } List<Object> asList = Arrays.asList(args); Signature signature = point.getSignature(); String name = signature.getName(); try { try { System.out.println("【事务日志】,【前置通知】,参数为:" + name + "方法为:" + asList); } finally { System.out.println("【事务日志】,【后置通知】,参数为:" + name + "方法为:" + asList); } System.out.println("【事务日志】,【返回通知】,参数为:" + name + "方法为:" + asList); } catch (Exception e) { // TODO: handle exception System.out.println("【事务日志】,【异常通知】,参数为:" + name + "方法为:" + asList); } return object; } }
环绕通知一定要返回Object对象的值,不然不会执行目标方法的内容体,即不会进入实现类方法体内。
跟配置的四个通知的比较,环绕通知的形式为:
try{
try{
前置通知
}
finally{
后置通知
}
返回通知
}
catch{
异常通知
}