1.Spring AOP
Spring aop基于动态代理实现的
1.1通知类型
- 前置通知(before)
- 最终后置通知(after[方法之心之后通知,无论方法成功,失败])
- 后置通知(afterRuning[方法成功返回之后才会通知])
- 环绕通知(around)
- 异常通知(afterThorwing[抛出异常后通知])
1.2动态代理过程
a.代理类
package spring.aop.impl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import spring.aop.service.ProxyService;
/**
* JDK动态代理实现过程
* @author 恒安
*
*/
public class JdkInvocationHandler implements InvocationHandler{
private ProxyService proxyService; //被代理的接口
public Object getInstance (ProxyService target){
this.proxyService=target;
Class classz=this.proxyService.getClass();
return Proxy.newProxyInstance(classz.getClassLoader(), classz.getInterfaces(), this);
}
public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
// TODO Auto-generated method stub
System.out.println("调用之前");
Object pojo=method.invoke(this.proxyService,arg2);
System.out.println("调用之后");
return pojo;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import spring.aop.service.ProxyService;
/**
* JDK动态代理实现过程
* @author 恒安
*
*/
public class JdkInvocationHandler implements InvocationHandler{
private ProxyService proxyService;
public Object getInstance (ProxyService target){
this.proxyService=target;
Class classz=this.proxyService.getClass();
return Proxy.newProxyInstance(classz.getClassLoader(), classz.getInterfaces(), this);
}
public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
// TODO Auto-generated method stub
System.out.println("调用之前");
Object pojo=method.invoke(this.proxyService,arg2);
System.out.println("调用之后");
return pojo;
}
}
b.被代理接口
package spring.aop.service;
public interface ProxyService {
public void add();
public void delete();
}
c.接口实现类
package spring.aop.impl;
import spring.aop.service.ProxyService;
public class Proxy implements ProxyService{
public void add() {
System.out.println("增加用户");
}
public void delete() {
System.out.println("删除用户");
}
}
d.代理测试
package spring.aop.test;
import spring.aop.impl.JdkInvocationHandler;
import spring.aop.impl.Proxy;
import spring.aop.service.ProxyService;
public class TestAop {
// https://blog.csdn.net/bluetjs/article/details/52263410
// https://www.jianshu.com/p/3616c70cb37b
public static void main(String[] args) {
ProxyService proxyService=new Proxy();
ProxyService proxy=(ProxyService) new JdkInvocationHandler().getInstance(proxyService);
proxy.add();
}
}
e.测试结果
调用之前
增加用户
调用之后
事物:
捕获异常回滚,引用别人连接。https://blog.csdn.net/ljyhust/article/details/73431968?locationNum=5&fps=1