AOP (Aspect Oriented Programing)
传统方法实现数据库事务管理,逻辑与事务混杂在一起,较为混乱,使用aop可以将逻辑与事务管理分开
public class ViewSpaceService{
private TransactionManager transManager;
private PerformanceMonitor pmonitor;
private ViewSpaceDao viewSpaceDao;
private ViewPointDao viewPointDao;
public void deleteViewPoint(int pointId){
pmonitor.start();
transManager.beginTransaction();
viewPonitDao.deleteViewPoint(pointId);
transManager.commit();
pmonitor.end();
}
public void addViewSpace(ViewSpace viewSpace){
pmonitor.start();
transManager.beginTransaction();
viewSpaceDao.addViewSpace(viewSpace);
transManager.commit();
pmonitor.end();
}
}
- AOP术语
- 切面aspect//由切点和增强组成
- 连接点joinpoint//一段程序代码拥有一些具有边界性质的特定点,成为连接点。
- 切点pointcut//定位特定连接点
- 通知(增强)advice//织入目标连接点上的一段代码
- 目标对象target//增强逻辑织入目标类
- 织入weaving//将增强添加到目标类具体连接点上的过程
- 引入introduction//特殊增强,为类添加一些属性和方法
- 代理Proxy//AOP织入增强后,产生一个结果类
aop简单实例
public class Target{
public void execute(String name){
Syste.out.println("程序开始执行:"+name);
}
}
public class LoggerExecute implements MethodInterceptor{
public Object invoke(MethodInvocation invocation)throws Throwable{
before();
invocation.proceed();
return null;
}
private void before(){
System.out.println("程序开始执行");
}
}
public class Manager{
public static void main(String[] args){
Target target = new Target();
ProxyFactory di = new ProxyFactory();
di.addAdvice(new LoggerExecute());
di.setTarget(target);
Target proxy = (Target)di.getProxy();
proxy.execute("AOP的简单实现");
}
}