移:AOP技术原理

AOP技术原理

AOP在JDK1.3开始被支持,体现在java.lang.reflect.InvocationHandler和Proxy类。对于InvocationHandler的子类,都会被执行invoke方法代替原先的方法。

例如有一个类Service,我们需要在Service的所有方法前加上事务管理代码,那么需要定义一个ServiceProxy继承自InvocationHandler,它包含实例Service。代码如下

public class ServiceProxy implements InvocationHandler{

 private Service _service;
 private Class interfaceType;
 
 private ServiceProxy(Service service, Class intf) {
   service = service;
   interfaceType = intf;
 }

  public static Object newInstance(Class intf, Service service) {
    return Proxy.newProxyInstance(service.getClass().getClassLoader(),new Class[]{intf},new ServiceProxy(service, intf)
  );
 }

  public getService

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    //加上事务管理代码,然后执行此方法

  }

}

还需要一个Bean工厂获得代理的Service

Service service = (Service) ServiceProxy.newInstance(Service.class, new GenericService();

这样,调用Service类之前做任何事情都会被加上事务管理代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值