一: 概念
Aspect,常譯為“方面”,是對施加于不同Class執行個體的相同問題域的抽象。<o:p></o:p>
二: 參與者<o:p></o:p>
(1) Pointcut: ”方面”的切點--用來決定是否執行Advice的謂詞
(2) Advice: 對”方面”的處理<o:p></o:p>
(3) Advisor: Pointcut和Advice的粘合劑<o:p></o:p>
三:Step-by-step
1 Bean: IShape, Rectange, Circle(代碼忽略)
IShape.java:IShape接口
- package com.rainsoft.exercise1.aop;
- public interface IShape {
- void draw();
- }
<o:p> Rectange.java:IShape的一個實作
- package com.rainsoft.exercise1.aop;
- public class Rectange implements IShape {
- public void draw() {
- System.out.println("Rectange is drawn.");
- }
- }
Note:
(1) SpringAOP Framework預設通過Dynamic Proxy實作,是以要定義接口;而且接口程式設計被強烈建議
2 Advice:以MethodBeforeAdvice為例
TimestampMethodBeforeAdvice.java
- package com.rainsoft.exercise1.aop;
- import java.lang.reflect.Method;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.springframework.aop.MethodBeforeAdvice;
- public class TimestampMethodBeforeAdvice implements MethodBeforeAdvice {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");
- public void before(Method method, Object[] args, Object target)
- throws Throwable {
- System.out.println(df.format(new Date()) + ":entering method - "
- + method.getName());
- }
- }
Note:
(1) Spring AOP Frame内置5種Advice,所有Advice都從org.aopalliance.aop.Advice繼承來
</o:p>
Before advice | org.springframework.aop.BeforeAdvice; org.springframework.aop.MethodBeforeAdvice |
After returning advice | org.springframework.aop.AfterReturningAdvice |
After throwing advice | org.springframework.aop.ThrowsAdvice |
After (finally) advice | ? |
Aroud advice | ? |
3 Config:
spring-aop-demo.xml xml version="1.0" encoding="UTF-8"?> > <beans> <bean id="rect" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>com.rainsoft.exercise1.aop.IShapevalue> property> <property name="target"> <ref local="rectTarget"/> property> <property name="interceptorNames"> <list> <value>timestampAdvisorvalue> list> property> bean> <bean id="rectTarget" class="com.rainsoft.exercise1.aop.Rectange">bean> <bean id="timestampAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="timestampAdvice"/> property> <property name="pattern"> <value>com\.rainsoft\.exercise1\.aop\.IShape\.drawvalue> property> bean> <bean id="timestampAdvice" class="com.rainsoft.exercise1.aop.TimestampMethodBeforeAdvice"/> beans>
4 主程式
Main.java package com.rainsoft.exercise1.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class Main { public static void main(String[] args) { try { ApplicationContext ctx = new FileSystemXmlApplicationContext("spring-aop-demo.xml"); IShape shape = (IShape)ctx.getBean("rect"); shape.draw(); } catch (Exception ex) { ex.printStackTrace(); } } }
5 運作結果
2006-12-05 01/32/03:entering method - draw Rectange is drawn.