一: 概念
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.