什么是JAVA动态代理?
百度百科AOP:
AOP在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
个人理解是 拦截直接访问的对象,对它增强,方法可以进行改造,扩展。Spring是IOC和动态代理结合出来的伟大编程思想,千锤百炼构造的框架体系,它的实践结果,成为了我们学习开发时的规范,遵循此,实现了一个又一个功能模块。
学习SpringAOP之前一定要补充JAVA动态代理的一些基础,需要尝试的同学,不要复制粘贴运行,最好敲出来改改,哪怕就改个类名,多试试、多思考。
/**
* 人
*/
public interface Person {
/**
* 一日三餐
* @param c
* @return
*/
Person eat(String c);
/**
* 思想需要会飞
* @param f
* @return
*/
Person fly(String f);
}
/**
* 人会做很多事
*/
public class Action implements Person {
/**
* 一日三餐
* @param c
* @return
*/
@Override
public Person eat(String c) {
System.out.println(c+"吃饱了,心情很好!");
return this;
}
/**
* 梦想着飞
* @param f
* @return
*/
@Override
public Person fly(String f) {
System.out.println(f+"-飞呀飞呀!");
return this;
}
}
public class App {
public static void main(String[] args) {
Person e = new Action();
e.eat("香蕉").fly("坐飞机");
}
}
运行结果:
香蕉吃饱了,心情很好!
坐飞机-飞呀飞呀!
不改变java代码,利用动态代理在执行 eat() 时 ,执行一些其他操作,比如异常,日志的输出~
实现一个InvocationHandler动态代理接口
public class ActionInvocationHandler implements InvocationHandler {
private final Person person;
public ActionInvocationHandler(Person person) {
this.person = person;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
try {
System.out.println("Before---------进入invocation动态代理-------");
System.out.println("method:"+method.getName());
if (method.getName().equals("action")) {
if (args[0].toString().equals("苹果")) {//假设是苹果时出异常
System.out.println(args[0].toString() + "-不喜欢吃,抛出异常。");
int[] arr = {};
int a = arr[0];// 制造数组越界异常a
}
}else if(method.getName().equals("fly")){
System.out.println("---------梦想自己会飞-------");
}
Object invok = method.invoke(person, args);
System.out.println("After---------离开invocation动态代理-------");
return invok;
} catch (Exception e) {
System.out.println("发生异常---------Exception-------:" + e);
} finally {
System.out.println("---------finally-------");
}
return proxy;
}
}
修改测试类
public class App {
public static void main(String[] args) {
Person a = (Person) Proxy.newProxyInstance(e.getClass().getClassLoader(), e.getClass().getInterfaces(),new ActionInvocationHandler(e));
a.eat("米饭");
a.eat("苹果");
a.fly("坐飞机");
}
}
a.eat(“米饭”)
Before---------进入invocation动态代理-------
method:eat
---------action方法,你吃的什么?-------
米饭吃饱了,心情很好!
After---------离开invocation动态代理-------
---------finally-------
a.eat(“苹果”)
Before---------进入invocation动态代理-------
method:eat
---------action方法,你吃的什么?-------
苹果-不喜欢吃,抛出异常。
---------Exception-------:java.lang.ArrayIndexOutOfBoundsException: 0
---------finally-------
a.eat(“坐飞机”)
Before---------进入invocation动态代理-------
method:fly
---------梦想自己会飞-------
坐飞机-飞呀飞呀!
After---------离开invocation动态代理-------
---------finally-------
SpringAOP本质是不是实现此类功能?我们也要有目的,赶快成长,入了这行,不思进取,到一定阶段会感到越来越渺小,尤其对整个JAVA体系掌握的不全面。