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;//返回动态代理的对象
}
}