Spring_AOP基于JDK的实现原理

Spring Aop 面向切面编程:

动态代理模式

被代理类:

package com.aowin.structure.proxy.dynamicproxy;

public interface SaleTicket {
	void sale();
}

 代理类:

package com.aowin.structure.proxy.dynamicproxy;

public class Station implements SaleTicket{

	public void sale() {
		System.out.println("sale a ticket.....");
	}

}

 拦截器:

package com.aowin.structure.proxy.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;


//代理行为
public class MyInvocationHandler implements InvocationHandler{
	
	//station对象
	private Object target ;
	
	public MyInvocationHandler(Object target) {
		super();
		this.target = target;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("in proxy method....");
		System.out.println("pay 5 yuan tip fee.....");
		Object obj = method.invoke(target, args); //通过反射机制调用目标对象的方法
		return obj;
	}

}

 进行切面操作业务逻辑:

package com.aowin.structure.proxy.dynamicproxy;

import java.lang.reflect.Proxy;

public class Test {

	public static void main(String[] args) {
		//目标对象
		Station target = new Station();
		//代理行为
		MyInvocationHandler mih = new MyInvocationHandler(target);
		//代理对象
		SaleTicket proxy = (SaleTicket) Proxy.newProxyInstance(Test.class.getClassLoader(),
				target.getClass().getInterfaces(), mih);
		//待用代理对象的方法,JVM将执行代理行为的invoke方法
		proxy.sale();
		
		System.out.println("done");
	}
	
}
 

 

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