spring中的ioc,aop。动态代理

spring ioc aop 的原理,

IOC(反转控制):对成员变量的赋值的控制权从代码中反转到配置文件中。
AOP:Aspect(切面) Oriented(面向) Programming(编程),面向切面编程


AOP
面向切面编程

划一箭头,竖线就是AOP

一个方法正运行着,想在前后加些日志(例如:(用户保存开始)(用户保存完毕))

transactionbegin(事物开始),transactioncommit(事物结束)
怎么实现
动态代理
1.如果实现了Interface就用jdk中的proxy+invocationHandler就可以实现
2.使用java sest操作二进制码可以完成


AOP主要用在什么地方
做权限检查,做日志,做性能,做审计,做transaction

在项目怎么用
主要用在申明式事物管理上

 

 

 

写一个ArrayList类的代理,其内部实现和ArrayList中完全相同的功能,
 并可以计算每个方法运行的时间。

 

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class MyArrayList<T>{
 
 public static void main(String[] args) {
  ArrayList<Integer> al=new ArrayList<Integer>();
  for(int i=0;i<100000;i++){
   
   al.add((int)Math.random()*10);
  }
  
  Collection proxy=new MyArrayList<Integer>().getMothedTime(al);
//  proxy.size();//获取al对象大小的方法
  proxy.toArray();
  proxy.toString();
  System.out.println(proxy.size());
 }
 
 
 
 
 public Collection getMothedTime(final ArrayList<T> al){
  
  Collection proxy=(Collection)Proxy.newProxyInstance(//创建出动态代理的对象
    Collection.class.getClassLoader(),
    new Class[]{Collection.class},
    new InvocationHandler() {
     
      @Override
     public Object invoke(Object proxy, Method method, Object[] args)
       throws Throwable {
      // TODO Auto-generated method stub
      
      long start=System.nanoTime();
      Object retVal=method.invoke(al, args);
      long end=System.nanoTime();
      System.out.println(method.getName()+"方法的运行时间是:"+(end-start)+"nns");//打印方法运行时间
      
      
      return retVal;
     }
    });
  return proxy;//返回动态代理的对象
 }
 
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值