Java笔记

知识点总结


AOP相关术语

<h1>AOP 相关术语</h1> <pre><code>Joinpoint(连接点): 所谓连接点是指那些被拦截到的点 在spring中这些点指的是方法 因为Spring只支持方法类型的连接点 Pointcut(切入点): 所谓切入点是指我们要对那些Joinpoint 进行拦截的定义 Advice(通知/增强):所谓通知是指拦截Joinpoint 之后所要做的事情就是通知 通知分为’前置通知‘ ’后置通知‘ ’异常通知‘ ’最终通知‘ ’环绕通知(切面要完成的功能)‘ Introduction(引介): 引介是一种特殊的通知再不修改类代码的前提下 Introduction可以在运行期间为类动态添加一些方法或者Field Target(目标对象): 代理的目标对象 Weaving(织入): 是值把增强应用到目标对象来创建新的代理对象的过程 Spring采用动态代理织入 而AspectJ采用编译期织入和类装载期来织入 Proxy(代理): 一个类被Aop织入增强后,就产生一个结果代理类 Aspect(切面): 是切入点和通知(引介)的结合</code></pre> <h3>(Joinpoint)连接点</h3> <pre><code>指的是可以被拦截到的点 * 增删改查这些方法都可以被增强 这些方法被称为连接点</code></pre> <h3>(Pointcut)切入点</h3> <pre><code>指的是真正被拦截到的点 只想对Save 方法进行增强(做权限校验) save方法就称为一个切入点</code></pre> <h3>Advice(通知/增强)</h3> <pre><code>指拦截后要做的事情 对save 方法做权限校验 权限校验的方法称为通知 之后所要做的事情就是通知 通知分为 ’前置通知‘ ’后置通知‘ ’异常通知‘ ’最终通知‘ ’环绕通知(切面要完成的功能)‘</code></pre> <h3>Target(被增强的对象)</h3> <pre><code>被增强的对象(UserDaoImpl) 就是要增强的对象</code></pre> <h3>Weaving(织入)</h3> <pre><code>将Advice应用到Target的过程 将权限校验引用到增强对象(UserDaoImpl)的save方法的过程</code></pre> <h3>Proxy(代理):</h3> <pre><code>被应用了增强后 产生一个代理对象</code></pre> <h3>Aspect(切面)</h3> <pre><code>切入点和通知的组合</code></pre> <h4>动态生成代理类</h4> <pre><code class="language-java"> @Test public void demoA(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserServiceDao userService = (UserServiceDao)applicationContext.getBean("UserService"); // UserServiceDao userService = new UserService(); /* 动态权限校验 */ UserServiceDao mySpringJdk = (UserServiceDao)new MySpringJdk(userService).CreateProxy(); mySpringJdk.deleted(); mySpringJdk.insert(); mySpringJdk.update(); mySpringJdk.select(); } public class MySpringJdk implements InvocationHandler { public UserServiceDao userService; public MySpringJdk(UserServiceDao userService){ this.userService = userService; } public Object CreateProxy(){ Object proxy = Proxy.newProxyInstance(userService.getClass().getClassLoader(),userService.getClass().getInterfaces(),this); return proxy; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("insert".equals(method.getName())){ System.out.println("权限校验"); return method.invoke(userService,args); } return method.invoke(userService,args); } }</code></pre> <h2>cglib 动态生成代理类</h2> <pre><code class="language-java"> private UserServiceDao userService; public MySpringCglibJdk(UserServiceDao userService){ this.userService = userService; } public Object CreateProxy(){ // 创建核心类 Enhancer enhancer = new Enhancer(); // 设置父类 enhancer.setSuperclass(userService.getClass()); // 设置回调 enhancer.setCallback(this); // 生成代理 Object proxy = enhancer.create(); return proxy; } public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if ("insert".equals(method.getName())){ System.out.println("权限校验"); return methodProxy.invokeSuper(proxy,args); } return methodProxy.invokeSuper(proxy,args); }</code></pre>

页面列表

ITEM_HTML