1.创建bean
创建接口
package com.spring.aop.beans;
public interface Calculator {
int add(int a,int b);
int sub(int a,int b);
int mul(int a,int b);
int div(int a,int b);
}实现接口
package com.spring.aop.beans;
import org.springframework.stereotype.Repository;
@Repository(value = "calculator")
public class CalculatorImpl implements Calculator {
@Override
public int add(int a, int b) {
int result = a + b;
return result;
}
@Override
public int sub(int a, int b) {
int result = a - b;
return result;
}
@Override
public int mul(int a, int b) {
int result = a * b;
return result;
}
@Override
public int div(int a, int b) {
int result = a / b;
return result;
}
}
2.创建java类
package com.spring.log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class LoggingProxy {
//被代理的对象
private Object target;
public LoggingProxy(Object target) {
this.target = target;
}
public Object getProxy() {
//获取被代理对象的类加载器
ClassLoader classLoader =target.getClass().getClassLoader();
//获取被代理对象实现的接口
Class<?>[] interfaces = target.getClass().getInterfaces();
Object proxy= Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
/*
参数说明
invoke方法中就是要执行的扩展的功能
该方法中参数的说明:
proxy:传入的代理对象
method:要调用的方法
args:调用方法时传入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//获取方法名
String methodName =method.getName();
System.out.println("Logging: The method "+methodName+"begins with"+ Arrays.toString(args));
//执行方法,即方法的调用转到被代理对象上
Object result=method.invoke(target,args);
System.out.println("Logging: The method "+methodName+"returns"+ result);
return result;
}
});
return proxy;
}
}
3.测试
/*
测试动态代理
*/
@Test
public void testProxy(){
Calculator cal = new CalculatorImpl();
//获取代理对象
Calculator calculator = (Calculator) new LoggingProxy(cal).getProxy();
//调用加减乘除的方法
calculator.add(10,2);
calculator.sub(10,2);
calculator.mul(10,2);
calculator.div(10,2);
}

版权声明:本文为qq_43555873原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。