动态代理类(Proxy)
使用一个动态代理类(Proxy),通过拦截一个对象的行为并添加我们需要的功能来完成。Java中的java.lang.reflect.Proxy类 和java.lang.reflect.InvocationHandler接口为我们实现动态代理类提供了一个方案,但是该方案针对的对象要实现某些接 口;如果针对的目的是类的话,cglib为我们提供了另外一个实现方案。
一、接口的实现方案:
java 代码
- public interface StudentInfoService{
- void findInfo(String studentName);
- }
- public class StudentInfoServiceImpl implements StudentInfoService{
- public void findInfo(String name){
- System.out.println("你目前输入的名字是:"+name);
- }
- }
- import org.apache.log4j.Logger;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Proxy;
- import java.lang.reflect.Method;
- public class MyHandler implements InvocationHandler{
- private Object proxyObj;
- private static Logger log=Logger.getLogger(MyHandler.class);
- public Object bind(Object obj){
- this.proxyObj=obj;
- return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
- }
- public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
- Object result=null;
- try{
- //请在这里插入代码,在方法前调用
- log.info("调用log日志方法"+method.getName());
- result=method.invoke(proxyObj,args); //原方法
- //请在这里插入代码,方法后调用
- }catch(Exception e){
- e.printStackTrace();
- }
- return result;
- }
- }
实现一个工厂,为了方便我们使用该拦截类(AOPFactory.java):
java 代码
- public class AOPFactory{
- private static Object getClassInstance(String clzName){
- Object obj=null;
- try{
- Class cls=Class.forName(clzName);
- obj=(Object)cls.newInstance();
- }catch(ClassNotFoundException cnfe){
- System.out.println("ClassNotFoundException:"+cnfe.getMessage());
- }catch(Exception e){
- e.printStackTrace();
- }
- return obj;
- }
- public static Object getAOPProxyedObject(String clzName){
- Object proxy=null;
- MyHandler handler=new MyHandler();
- Object obj=getClassInstance(clzName);
- if(obj!=null) {
- proxy=handler.bind(obj);
- }else{
- System.out.println("Can't get the proxyobj");
- //throw
- }
- return proxy;
- }
- }
使用该工厂类
java 代码
- public class ClientTest{
- public static void main(String[] args){
- StudentInfoService studentInfo=(StudentInfoService)AOPFactory.getAOPProxyedObject("StudentInfoServiceImpl");
- studentInfo.findInfo("阿飞");
- }
- }