1. 兩種方式:
a) 使用Annotation
b) 使用xml
2. Annotation
a) 加上對應的xsd文件spring-aop.xsd
b) beans.xml <aop:aspectj-autoproxy />
c) 此時就可以解析對應的Annotation了
d) 建立我們的攔截類
e) 用@Aspect註解這個類
f) 建立處理方法
g) 用@Before來註解方法
h) 寫明白切入點(execution …….)
i) 讓spring對我們的攔截器類進行管理@Component
3. 常見的Annotation:
a) @Pointcut 切入點聲明以供其他方法使用 , 例子如下:
@Aspect
@Component
publicclass LogInterceptor {
@Pointcut("execution(public * com.bjsxt.dao..*.*(..))")
publicvoid myMethod(){}
@Around("myMethod()")
publicvoidbefore(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("method before");
pjp.proceed();
}
@AfterReturning("myMethod()")
publicvoid afterReturning() throws Throwable{
System.out.println("method afterReturning");
}
@After("myMethod()")
publicvoid afterFinily() throws Throwable{
System.out.println("method end");
}
}
b) @Before 發放執行之前織入
c) @AfterReturning 方法正常執行完返回之後織入(無異常)
d) @AfterThrowing 方法拋出異常後織入
e) @After 類似異常的finally
f) @Around 環繞類似filter , 如需繼續往下執行則需要像filter中執行FilterChain.doFilter(..)對象一樣 執行 ProceedingJoinPoint.proceed()方可,例子如下:
@Around("execution(* com.bjsxt.dao..*.*(..))")
publicvoidbefore(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("method start");
pjp.proceed();//類似FilterChain.doFilter(..)告訴jvm繼續向下執行
}
4. 織入點語法
a) void !void
b) 參考文檔(* ..)
如果execution(* com.bjsxt.dao..*.*(..))中聲明的方法不是接口實現則無法使用AOP實現動態代理,此時可引入包” cglib-nodep-2.1_3.jar” 後有spring自動將普通類在jvm中編譯爲接口實現類,從而打到可正常使用AOP的目的.
5. xml配置AOP
a) 把interceptor對象初始化
b) <aop:config
i. <aop:aspect …..
1. <aop:pointcut
2. <aop:before
例子:
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
<aop:config>
<!-- 配置一個切面 -->
<aop:aspect id="point" ref="logInterceptor">
<!-- 配置切入點,指定切入點表達式 -->
<!-- 此句也可放到 aop:aspect標籤外依然有效-->
<aop:pointcut
expression=
"execution(public* com.bjsxt.service..*.*(..))"
id="myMethod"/>
<!-- 應用前置通知 -->
<aop:before method="before"pointcut-ref="myMethod" />
<!-- 應用環繞通知需指定向下進行 -->
<aop:around method="around"pointcut-ref="myMethod" />
<!-- 應用後通知 -->
<aop:after-returning method="afterReturning"
pointcut-ref="myMethod"/>
<!-- 應用拋出異常後通知 -->
<aop:after-throwing method="afterThrowing"
pointcut-ref="myMethod"/>
<!-- 應用最終通知 -->
<aop:after method="afterFinily"
pointcut="execution(public* om.bjsxt.service..*.*(..))" />
</aop:aspect>
</aop:config>