Spring的環繞通知
阿新 • • 發佈:2017-08-31
掃描 cut object ued exe one ati inter instance
首先加入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) { intresult=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 publicvoid 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{
異常通知
}
Spring的環繞通知