這篇介紹的是最為常見的切面編程
首先介紹的是通過注解@Aspect來配置AOP類
@Component
@Aspect
public?class?Acsep?{//定義切入點@Pointcut("execution(*?com.test.*.*(..))")//切面公式public?void?aspect(){ }//執行方法之前@Before("aspect()")public?void?before(JoinPoint?joinPoint)?throws?Exception{System.out.println("執行方法開始");}//執行方法之后@After("aspect()")public?void?after(JoinPoint?joinPoint){System.out.println("執行方法之后");}//環繞通知@Around("aspect()")public?void?around(JoinPoint?joinPoint){try?{System.out.println("執行方法之前"+joinPoint.getArgs());Object?aaa?=((ProceedingJoinPoint)?joinPoint).proceed();System.out.println("執行方法之后"+aaa);}?catch?(Throwable?e)?{e.printStackTrace();}}//配置后置返回通知@AfterReturning("aspect()")public?void?afterReturn(JoinPoint?joinPoint){System.out.println("在after后增強處理");}//配置拋出異常后通知@AfterThrowing(pointcut="aspect()",?throwing="ex")public?void?afterThrow(JoinPoint?joinPoint,?Exception?ex){System.out.println("異常處理");}
}
其次可以配置XML的方式進行AOP
<!--?首先定義配置bean??--><bean?id?=?"webAcsep"?class="com.cn.cis.interceptor.WebAcsep"/><aop:config><!--?把beanid為webAcsep的類定義為AOP類??--><aop:aspect?id="myAop"?ref="webAcsep"><!--?配置切入點??--><aop:pointcut?id="target"?expression="execution(*?com.test.*.*(..))"/><!--?在方法執行之前執行AOP類的doBefore?--><aop:before?method="doBefore"?pointcut-ref="target"/><!--?在方法執行之后執行AOP類的doAfter??--><aop:after?method="doAfter"?pointcut-ref="target"/></aop:aspect></aop:config>
類為
public?class?WebAcsep?{public?void?doBefore(JoinPoint?jp){System.out.println("===========執行前置通知============");}???public?void?doAfter(JoinPoint?jp){System.out.println("===========執行最終通知============");}
}
還有一種利用自定義注解去切,這種使用靈活,我一般在開發中使用的比較多
首先自定義注解
@Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public?@interface?DemoPro{}
然后去配置XML
<bean?id?=?"webAcsep"?class="com.cn.cis.interceptor.WebAcsep">?</bean><aop:config><aop:aspect?id="myAop"?ref="webAcsep"><!--?公式為切使用DemoPro注解的方法--><aop:pointcut?id="target"?expression="@annotation(com.cn.cis.anntion.DemoPro)"/><aop:before?method="doBefore"?pointcut-ref="target"/><aop:after?method="doAfter"?pointcut-ref="target"/></aop:aspect></aop:config> </beans>
這樣只要給方法加上定義的注解,會自動切
?@DemoPropublic?void?Test(){System.out.println("邏輯");}
比如說有的類需要加入特定的日志,可以按照此方法使用。在需要特定日志的方法加入注解。
轉載于:https://blog.51cto.com/13064904/1979616