实现动态代理(Java和spring)

一、Java实现动态代理

1、创建接口

package com.oyy.mw.biz.i;

public interface Cal {
    
    public int add(int num1,int num2);
    public int sub(int num1,int num2);
    public int mul(int num1,int num2);
    public int div(int num1,int num2);
    
}

2、创建实现类

package com.oyy.mw.biz;

import com.oyy.mw.biz.i.Cal;

public class CalImpl implements Cal{

    public int add(int num1, int num2) {
        int result = num1+num2;
        return result;
    }

    public int sub(int num1, int num2) {
        int result = num1-num2;
        return result;
    }

    public int mul(int num1, int num2) {
        int result = num1*num2;
        return result;
    }

    public int div(int num1, int num2) {
        int result = num1/num2;
        return result;
    }

}

3、创建Java动态代理实现类

package com.oyy.mw.biz;

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

public class MyInvocationHandler implements InvocationHandler {
    
    Object obj = null;
    
    /**
     * @param obj 接受传入的真实对象
     * @return 返回代理对象
     */
    public Object bind(Object obj){
        this.obj = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), 
                obj.getClass().getInterfaces(),
                this);
    }
    
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println(method.getName()+"的参数是:"+Arrays.toString(args));
        //调用方法,返回该方法返回的结果
        Object result  = method.invoke(obj, args);
        System.out.println(method.getName()+"的结果是:"+result);

        return result;
    }

}

4、测试动态代理

package com.oyy.mw.test;

import com.oyy.mw.biz.CalImpl;
import com.oyy.mw.biz.MyInvocationHandler;
import com.oyy.mw.biz.i.Cal;

public class Test {
    public static void main(String[] args) {
        Cal cal1 = new CalImpl();
        MyInvocationHandler handler  = new MyInvocationHandler();
        Cal cal = (Cal)handler.bind(cal1);
        cal.add(10, 3);
        
        cal.sub(10, 3);
        cal.mul(10, 3);
        cal.div(10, 3);
    }
}

5、打印结果

 

二、spring实现动态代理(AOP)

  1、创建接口

package com.oyy.mw.aspects.i;

public interface Cal {
    
    public int add(int num1,int num2);
    public int sub(int num1,int num2);
    public int mul(int num1,int num2);
    public int div(int num1,int num2);
    
}

  2、创建实现类

package com.oyy.mw.aspects;

import org.springframework.stereotype.Component;

import com.oyy.mw.aspects.i.Cal;

@Component
public class CalImpl implements Cal{

    public int add(int num1, int num2) {
        int result = num1+num2;
        return result;
    }

    public int sub(int num1, int num2) {
        int result = num1-num2;
        return result;
    }

    public int mul(int num1, int num2) {
        int result = num1*num2;
        return result;
    }

    public int div(int num1, int num2) {
        int result = num1/num2;
        return result;
    }

}

  3、配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.oyy.mw.aspects"></context:component-scan>
    
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

  4、spring切面的实现

package com.oyy.mw.aspects;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggerAspect {
    
    @Before("execution(public int com.oyy.mw.aspects.CalImpl.*(..))")
    public void before(JoinPoint joinPoint){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        //获取参数列表
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println(name+"的参数是:"+args);
    }
    
    @After("execution(public int com.oyy.mw.aspects.CalImpl.*(..))")
    public void after(JoinPoint joinPoint){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法结束");
    }

    @AfterReturning(value="execution(public int com.oyy.mw.aspects.CalImpl.*(..))",returning="result")
    public void afterReturn(JoinPoint joinPoint,Object result){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法的结果是"+result);
    }

    @AfterThrowing(value="execution(public int com.oyy.mw.aspects.CalImpl.*(..))",throwing="ex")
    public void afterThrowing(JoinPoint joinPoint,Exception ex){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法抛出异常:"+ex);
    }
    
}

  5、测试类

package com.oyy.mw.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.oyy.mw.aspects.CalImpl;
import com.oyy.mw.aspects.MyInvocationHandler;
import com.oyy.mw.aspects.i.Cal;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Cal cal = (Cal)context.getBean("calImpl");
        cal.div(10, 2);
    }
}

  6、运行结果

posted @ 2019-01-14 11:31  欧阳宇  阅读(872)  评论(0编辑  收藏  举报