Spring——AOP(面向切面編程)@AspectJ註解方式

要通過@AspectJ註解方式,實現Spring AOP ,需要三個步驟:

1.在配置文件中添加<aop:aspectj-autoproxy/>,啓動對@AspectJ註解的支持。

2.定義切面Bean,在這個類的開頭添加@AspectJ。

3.定義增強處理,在方法開頭用@Before、@After、@Around修飾。

——————————————————————————————————————————————————————————————————————————

1.在配置文件中添加<aop:aspectj-autoproxy/>,啓動對@AspectJ註解的支持。

<!-- 啓動對@AspectJ註解的支持 -->  
<aop:aspectj-autoproxy/> 

2.定義切面類,其他方法可以插入這個類裏的方法。在這個類的開頭添加@AspectJ。

// 使用@Aspect 定義一個切面類   
@Aspect  
public class LogAspect {  
        // 定義該類的其他內容   
        ...  
} 

3.定義增強處理,在方法開頭用@Before、@After、@Around修飾。

@Component  
@Aspect  
public class AopLog {  
      
    //方法執行前調用,插入前面。 
    @Before("execution (* com.zywang.services.impl.*.*(..))")  
    public void MyMethod() {  
        System.out.println("你們都可以來插入我");  
    }  
      
    //方法執行後調用,插入後面。  
    @After("execution (* com.zywang.services.impl.*.*(..))")  
    public void MyMethod() {  
        System.out.println("你們都可以來插入我");  
    }  
      
    //方法執行的前後調用,前後都插入。  
    @Around("execution (* com.zywang.services.impl.*.*(..))")  
    public Object MyMethod(ProceedingJoinPoint point) throws Throwable{  
        System.out.println("begin around");  
        Object object = point.proceed();  
        System.out.println("你們都可以來插入我");  
        return object;  
    }  
      
    //方法運行出現異常時調用,出現異常後插入。  
    @AfterThrowing(pointcut = "execution (* com.zywang.services.impl.*.*(..))",throwing = "ex")  
    public void MyMethod(Exception ex){  
        System.out.println("afterThrowing");  
        System.out.println(ex);  
    }  
}  

Before增強處理:

@Before("execution (* com.zywang.services.impl.*.*(..))")

@Before( pointout = "execution (* com.zywang.services.impl.*.*(..))" ) 

@Before( value = "execution (* com.zywang.services.impl.*.*(..))" )

這三種寫法都是對的。表示這些包裏的方法都是切入點,在執行這些方法之前要執行Before(),即也可以理解爲用Before()切入這些方法。

AfterReturning增強處理:

@AfterReturning(returning="rvt", pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))")

如果底下的函數有參數,則必須寫returning。

AfterThrowing 增強處理:

@AfterThrowing(pointcut ="execution(* cn.huaxia.spring.*.*(..))", throwing ="th")

After 增強處理:
Around 增強處理:

————————————————————————————————————————————————————————————

另外:我們可以申明切入點我們可以在多處使用。

Spring 切入點定義包含兩個部分:

  • 一個切入點表達式。
  • 一個包含不需要參數和方法體的切入點方法。
// 使用@Pointcut Annotation 時指定切入點表達式   
@pointcut("execution * transfer(..)")  
// 使用一個返回值爲void,方法體爲空的方法來命名切入點   
private void anyOldTransfer(){}  
  
// 使用上面定義的切入點   
@AfterReturning(pointcut="anyOldTransfer()", returning="reVal")  
public void writeLog(String msg, Object reVal){  
    ...  
} 


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章