利用Proxy实现Spring的AOP

前提:采用Proxy类方法,目标对象必须要实现接口,否则不能使用这个方法。
流程:主函数 --> 代理 -->  目标对象的方法。
 

示例情景:new一个学生类,传参name时就输出hello,没传name参数时就输出其他的。

首先创建接口:StudentInterface.java

package com.kobe.proxy;

	public interface StudentInterface {  
	    public void print();  
	}  

创建实现类:StudentBean.java

写上get和set方法,并写个带参数的构造方法

package com.kobe.proxy;

public class StudentBean implements StudentInterface {
	private String name;

	public StudentBean() {
	}

	public StudentBean(String name) {
		this.name = name;
	}

	public void print() {
		System.out.println("Hello World!");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

创建实现InvocationHandler接口的代理工厂类:ProxyFactory.java

并重写invoke方法

package com.kobe.proxy;

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

public class ProxyFactory implements InvocationHandler {
	private Object stu;

	public Object createStudentProxy(Object stu) {
		this.stu = stu;
		return Proxy.newProxyInstance(
				stu.getClass().getClassLoader(), 
				stu.getClass().getInterfaces(), 
				this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		StudentBean s = (StudentBean) stu;
		Object object = null;
		if (s.getName() != null)
			object = method.invoke(stu, args);
		else
			System.out.println("name为空,已被代理类拦截");
		return object;
	}
}

创建测试类: Main.java

package com.kobe.proxy;


public class Main {

	public static void main(String[] args) {
		StudentInterface s1 = new StudentBean();
		ProxyFactory factory = new ProxyFactory();
		StudentInterface s2 = 
				(StudentInterface)factory.createStudentProxy(s1);

		s2.print();
	}

}

当  StudentInterface s1 = new StudentBean();  时

会被拦截,并打印出      name为空,已被代理类拦截

当  StudentInterface s1 = new StudentBean(“kobe”);  时

会打印出 Hello World!

猜你喜欢

转载自my.oschina.net/xiaozhiwen/blog/1788334