AOP,面向切面編程,利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程序的可重用性,同時提高了開發的效率。
AOP的主要功能:權限控制、事務管理 、日誌打印、性能統計、異常處理等
AOP的三大點:
(1)關注點——重複代碼
(2)切面——抽取重複代碼
(3)切入點——攔截哪些方法
AOP的通知有:前置通知、後置通知、運行通知、異常通知、環繞通知
一、註解方式實現AOP編程
1、在配置文件中開啓aop註解
<!--開啓aop註解-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
2、在Aop文件中編寫方法,添加註解(如:@Aspect、@Component、@Before等)
表達式execution(* cn.cxh.service..(…))這個表達式的意思是cn.cxh.service包下的文件都會被通知,如果想具體某個service的某個方法,可以這樣寫:execution(* cn.cxh.service.DeptService.add(…)),所以他的規則就是,那個不想具體,用*代替就可以了
@Aspect
@Component
public class Aop {
@Before("execution(* cn.cxh.service.*.*(..))")
public void bean(){
System.out.println("----------前置通知-----------");
}
@After("execution(* cn.cxh.service.*.*(..))")
public void commit(){
System.out.println("----------後置通知-----------");
}
@AfterReturning("execution(* cn.cxh.service.*.*(..))")
public void afterRun(){
System.out.println("----------運行通知-----------");
}
@AfterThrowing("execution(* cn.cxh.service.*.*(..))")
public void afterThrowing(){
System.out.println("----------異常通知-----------");
}
@Around("execution(* cn.cxh.service.*.*(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("----------環繞通知(前)-----------");
proceedingJoinPoint.proceed();
System.out.println("----------環繞通知(後)-----------");
}
}
二、XML方式實現AOP編程
1、配置文件中配置aop
這裏配置每個通知的method要與實際方法名相對應
<bean id="aop" class="cn.cxh.util.AopXml"></bean>
<aop:config>
<!--定義一個切點表達式,攔截哪些方法-->
<aop:pointcut id="pt" expression="execution(* cn.cxh.service.UserService.*(..))"/>
<!--切面-->
<aop:aspect ref="aop">
<aop:around method="around" pointcut-ref="pt"/>
<aop:before method="before" pointcut-ref="pt"/>
<aop:after method="after" pointcut-ref="pt"/>
<aop:after-returning method="afterReturning" pointcut-ref="pt"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pt"/>
</aop:aspect>
</aop:config>
2、在文件AopXml中只寫方法就可以了,不用添加註解
public class AopXml {
public void before(){
System.out.println("----------前置通知-----------");
}
public void after(){
System.out.println("----------後置通知-----------");
}
public void afterReturning(){
System.out.println("----------運行通知-----------");
}
public void afterThrowing(){
System.out.println("----------異常通知-----------");
}
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("----------環繞通知(前)-----------");
proceedingJoinPoint.proceed();
System.out.println("----------環繞通知(後)-----------");
}
}