1什么是AOP:AOP是面向切面編程,也就是說面向某個功能模塊編程,典型的應用就是Spring的聲明式事務,
Spring的AOP事務解析:
在以前的事務管理是要融合在邏輯代碼中的,在邏輯代碼中決定事務是否提交或者回滾,這樣很容易造成代碼難以維護,代碼冗余
但是使用spring的聲明式事務后,只需要在數據庫處理方法上注解事務,就可以對操作進行管理,事務的設置和邏輯代碼分開,容易維護
2AOP有什么作用
:面向切面編程,例如某個功能點,我們只需抽取橫切關注點,然后讓需要處理這些功能點的方法來使用代理的方式調用
3AOP有什么組成
1切面:橫切關注點被模塊化的對象---功能模塊化組成的對象
2通知:就是切面需要完成的功能---就是功能的實現方法1、方法2...
3連接點:就是程序執行的某個特定位置,例如方法前方法后,也是通知所關心的位置
4目標:被通知的對象,也是連接點所在的對象
5代理(Proxy): 向目標對象應用通知之后創建的對象
4AOP怎樣使用
1:抽取橫切關注點:也就是抽取我們需要面向切面編程的功能,然后模塊化對象
2:然后把模塊化對象聲明為切面
3:把模塊對象細粒化,把功能細分為各個方法
4:聲明通知和通知的連接點
登錄示例:
登錄前后需要調用某一個動能---->也就是橫切關注點
1切面:橫切關注點模塊化的對象--》loginCheck
package com.aop; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoginCheck { public void beforeLogin() { System.out.println("登錄前檢查---------->"); } public void afterLogin() { System.out.println("登錄后檢查---------->"); } }
2把模塊對象的功能細粒化,細分為各個方法上面代碼已經細化粒化的
3聲明通知和連接點:
@Before(value ="execution(* com.aop.entityService.*(..))")
public void beforeLogin(JoinPoint joinPoint) {
System.out.println(joinPoint.getSignature().getName()+"登錄前檢查---------->");
}
@After(value ="execution(* com.aop.entityService.*(..))")
public void afterLogin(JoinPoint joinPoint) {
System.out.println(joinPoint.getSignature().getName()+"登錄后檢查---------->"+joinPoint.getStaticPart().getSignature().getDeclaringType().getName());
}
login類:
package com.aop; import org.springframework.stereotype.Repository; @Repository public class entityService { private int id; private String name="jeremy"; public void login() { System.out.println(this.name+"登錄了------>"); } }
測試代碼:
public static void main(String[] args) throws SQLException { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); entityService entityService=applicationContext.getBean(entityService.class); entityService.login(); }
測試:
