spring aop

简单看了下spring aop的代码,所以做个笔记,不对的地方还望指正

spring aop 是实现上基于 java动态代理和cglib,

类 JdkDynamicAopProxy, Cglib2AopProxy, 他们都实现了接口AopProxy


当要获得一个bean时, spring 会检查这个bean是普通bean了还是factoryBean,就返回factorybean 的 getObject方法,让客户端得到一个已经被增强的代理类。有了这个代理类,其他问题就好办了,你懂的。。。。






cglib example:


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;


public class CglibProxy implements MethodInterceptor{
	
	 private Enhancer enhancer = new Enhancer(); 
	
	public Object getProxy(Class clazz){
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
	    return enhancer.create();
	}
	

	public Object intercept(Object arg0, Method arg1, Object[] arg2,
			MethodProxy arg3) throws Throwable {
		System.out.println(arg1.getName()+" start");
		Object result=arg3.invokeSuper(arg0, arg2);
		System.out.println(arg1.getName()+" end");
		return result;
	}
	
	
	public static void main(String[] args){
		CglibProxy proxy=new CglibProxy();
		Hello hello=(Hello)proxy.getProxy(Hello.class);
		hello.sayHello();
	}

}

你可能感兴趣的:(spring,AOP)