Spring的核心之一AOP,面向切面的编程和OOP相比较,优势在与AOP是对程序的横向的增强。
把程序比方成一个圆柱,AOP则是能横向把程序切开,再把自己无缝的织入,实现程序的横向增强。而OOP对程序的增强则需要以继承的方式,是把程序整体增强,AOP则只需要针对某一个点,对切入点进行增强。
Spring实现AOP是以代理的方式实现的,下面以两个例子,来讲解静态代理和动态代理。
静态代理,的原理是,面向接口的,代理对象,必须包含真实对象的引用,在执行真实对象的时候实现增强例如
定义一个借口
package com.yc.biz;
public interface ProductBiz {
public void addProduct();
}
实现一个真实类
package com.yc.biz.impl;
import com.yc.biz.ProductBiz;
public class ProductBizImpl implements ProductBiz {
public void addProduct() {
System.out.println("**********************************");
System.out.println("添加产品");
System.out.println("**********************************");
}
}
这一步是关键,建立代理类,上文提到了,代理类必须有真实类的引用如下
package com.yc.biz.impl;
import com.yc.biz.ProductBiz;
public class ProductBizRightProxy implements ProductBiz {
//代理类中必须有真实对象的引用
**private ProductBiz productBiz;**
**public ProductBizRightProxy(ProductBiz productBiz) {
this.productBiz = productBiz;
}**
public void addProduct() {
check();
productBiz.addProduct();
}
//增强功能
private void check(){
System.out.println("权限");
System.out.println("*****************************");
}
}
测试代码
import com.yc.biz.ProductBiz;
import com.yc.biz.impl.ProductBizImpl;
import com.yc.biz.impl.ProductBizLogProxy;
import com.yc.biz.impl.ProductBizRightProxy;
public class Test1 {
public static void main(String[] args) {
ProductBiz pb=new ProductBizImpl();
pb.addProduct();
ProductBiz pbl=new ProductBizRightProxy(pb);
pbl.addProduct();
}
执行的结果是
**********************************
添加产品
**********************************
权限
*****************************
**********************************
添加产品
**********************************
其中,执行代理类的时候就执行了真实类,同时执行了check()方法,即对真实类,进行了check()的增强。
由于是面向接口的,在传递引用时,可以把代理类也看作真实类,传递过去,就实现了多功能增强
这是一个日志代理
package com.yc.biz.impl;
import com.yc.biz.ProductBiz;
public class ProductBizLogProxy implements ProductBiz {
//代理类中必须有真实对象的引用
private ProductBiz productBiz;
public ProductBizLogProxy(ProductBiz productBiz) {
this.productBiz = productBiz;
}
public void addProduct() {
productBiz.addProduct();
log();
}
public void log(){
System.out.println("日志功能");
}
}
测试
package com.yc.test;
import com.yc.biz.ProductBiz;
import com.yc.biz.impl.ProductBizImpl;
import com.yc.biz.impl.ProductBizLogProxy;
import com.yc.biz.impl.ProductBizRightProxy;
public class Test1 {
public static void main(String[] args) {
ProductBiz pbl=new ProductBizLogProxy(new ProductBizImpl());
ProductBiz pb=new ProductBizRightProxy(pbl);
pb.addProduct();
}
}
执行结果:
权限
*****************************
**********************************
添加产品
**********************************
日志功能
可以看出来,实现了权限和日志的两项增强功能