aop概念
aop概念
aop術語
AOP實現方式1、spring-aop(使用xml文件實現AOP)
2、AspectJ(使用注解實現AOP)
概念:面向切面編程
作用:不用修改原來的類就可以添加新功能
aop術語
joinpoint 連接點:類中可以被增強的方法(其實就是類中的方法)
pointcut 切入點:類中實際被增強的方法(并不是所有的方法都被增強了)
advice 通知/增強:實際擴展功能的邏輯,有下面幾種類型before 前置增強:方法執行之前
after-returning 后置增強:方法正常執行之后,如果出現異常,則不能增強
after-throwing 異常增強:出現異常的時候
after 最終增強:一定會執行的增強,無論是否出現異常,相當于finally代碼塊
around 環繞增強:方法之前和之后執行
aspect 切面:把增強用到切入點的過程
target 目標:被增強方法所在的類
weaving 織入:將增強應用到目標的過程
AOP實現方式
Spring實現aop操作有兩種方式:
1、Spring-aop 2、AspectJ
1、spring-aop(使用xml文件實現AOP)
使用步驟
1、導包
spring-aop.jar、aspectjweaver.jar
<!-- 被增強的類 -->
<bean class="com.hemi.bean.Car" id="car"></bean>
<!-- 實施增強的類 -->
<bean class="com.hemi.bean.CarUtils" id="carUtils"></bean>
<!-- 配置aop -->
<aop:config>
<!-- 切入點:被增強的方法 -->
<aop:pointcut expression="execution(public void com.hemi.bean.Car.run(..))" id="pointcut1"/>
<!-- 切面:將切面運用到切入點的過程 -->
<aop:aspect ref="carUtils">
<aop:before method="show" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
標簽詳解
Some_Text
2、AspectJ(使用注解實現AOP)
使用步驟
1、導包 spring-aspects.jar、aspectjweaver.jar
2、通過xml文件開啟aspectj注解
<aop:aspectj-autoproxy/>
3、創建增強類
@Aspect//
1、標示該類是增強類public class StudentUtils {
//2、配置切入點,括號內是表達式
@Pointcut("execution(* com.hemi.bean.Student.study(..))") public void pointcut(){}
//3、前置增強,括號內寫切入點的名稱,即上面的方法名
@Before("pointcut()")
public void high(Joinpoint jp){
System.out.println("玩會手機。。。。");
jp.getArgs();//獲取參數
}
@Around("pointcut()")
public void show(ProceedingJoinpoint pjp){
//ProceddingJoinpointcut只有在環繞增強時可以用
pjp.getSignature().getDeclaringType();//獲取方法名 }}
注解詳解
Some_Text
重點關注
@After
Some_Text
@AfterThrowing
Some_Text
@Around
Some_Text