代码语言:javascript复制
public class ProxyFactory {
public static Object getAgent(Service target,Aop aop)
{
return Proxy.newProxyInstance(
//类加载器
target.getClass().getClassLoader(),
//目标对象实现的所有接口
target.getClass().getInterfaces(),
//代理功能的实现
new InvocationHandler() {
@Override
public Object invoke(
//生成的代理对象
Object proxy,
//正在调用的目标方法
Method method,
//目标方法的参数
Object[] args
) throws Throwable {
aop.before();
Object invoke = method.invoke(target,args);
aop.afeart();
return invoke;
}
}
);
}
}
代码语言:javascript复制public interface Aop {
default void before(){};
default void afeart(){};
default void end(){};
}
代码语言:javascript复制public class logAop implements Aop{
@Override
public void before() {
System.out.println("日志开启");
Aop.super.before();
}
}
代码语言:javascript复制public class TranAop implements Aop{
@Override
public void before() {
System.out.println("事物开启");
Aop.super.before();
}
@Override
public void afeart() {
System.out.println("事物进行");
Aop.super.afeart();
}
@Override
public void end() {
System.out.println("事物关闭");
Aop.super.end();
}
}
代码语言:javascript复制public interface Service {
void buy();
}
代码语言:javascript复制public class buyBook implements Service {
@Override
public void buy() {
System.out.println("buy BOOK");
}
}
代码语言:javascript复制public class buyShop implements Service {
@Override
public void buy() {
System.out.println("buy shop");
}
}