Spring框架之面向切面編程AOP(3.0)
基於Annotation的AOP配置
雖然在開發過程之中,90%的情況下對於AOP的控制基本上都是基於配置文件完成的,當然AOP本身爲了方便代碼的編寫,也可以使用Annotation進行控制;
1,修改applicationContext配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config />
<context:component-scan base-package="cn.mldn" />
<aop:aspectj-autoproxy/>
</beans>
2,修改SreviceProxy程序配置,讓其變爲Aonntation註解配置:
package cn.mldn.aop;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ServiceProxy {
@Before(value="execution(* cn.mldn.service..*.*(..)) and args(id)",argNames="id")
public void beforeMethod(Object obj) {
System.out.println("####### 【ServiceProxy】public void beforeMethod(){},參數內容:" + obj);
}
@After(value="execution(* cn.mldn.service..*.*(..))")
public void afterMethod() {
System.out.println("####### 【ServiceProxy】public void afterMethod(){}");
}
@AfterReturning(value="execution(* cn.mldn.service..*.*(..))",returning="v",argNames="v")
public void returnMethod(Object val) { // 處理返回值
System.out.println("####### 【ServiceProxy】public void returnMethod(){},返回值:" + val);
}
@AfterThrowing(value="execution(* cn.mldn.service..*.*(..))",throwing="e",argNames="e")
public void throwMethod(Exception e) { // 對異常進行處理
System.out.println("####### 【ServiceProxy】public void throwMethod(){},異常信息:" + e);
}
@Around(value="execution(* cn.mldn.service..*.*(..))")
public Object aroundMethod(ProceedingJoinPoint point) throws Throwable { // 調用具體的執行方法
System.out.println("@@@@@ 【環繞通知】aroundMethod() - before,參數:" + Arrays.toString(point.getArgs())); // 取得所有傳遞過來的參數
// 此時可以針對於參數接收後處理後再傳遞的操作
Object obj = point.proceed(new Object [] {"abc"}) ; // 自己來處理內容
System.out.println("@@@@@ 【環繞通知】aroundMethod() - after,返回結果:" + obj);
return true ; // 不按照結果返回數據
}
}
3,運行結果: