0
点赞
收藏
分享

微信扫一扫

Spring5深入浅出篇:Spring动态代理详解

止止_8fc8 1天前 阅读 3

Spring5深入浅出篇:Spring动态代理详解

视频地址

Spring动态代理详解

额外功能的详解

  • MethodBeforeAdvice分析
1. MethodBeforeAdvice接⼝作⽤:额外功能运⾏在原始⽅法执⾏之前,进⾏额外功能
操作。
public class Before1 implements MethodBeforeAdvice {
 /*
 作⽤:需要把运⾏在原始⽅法执⾏之前运⾏的额外功能,书写在before⽅法中
 Method: 额外功能所增加给的那个原始⽅法
 login⽅法
 register⽅法
 showOrder⽅法
 Object[]: 额外功能所增加给的那个原始⽅法的参数。String name,String
password
 User
 Object: 额外功能所增加给的那个原始对象 UserServiceImpl
 OrderServiceImpl
 */
 @Override
 public void before(Method method, Object[] args, Object target) throws Throwable {
 System.out.println("-----new method before advice log------");
 }
}
2. before⽅法的3个参数在实战中,该如何使⽤。
 before⽅法的参数,在实战中,会根据需要进⾏使⽤,不⼀定都会⽤到,也有可能都不⽤。
 Servlet{
 service(HttpRequest request,HttpResponse response){
 request.getParameter("name") -->
 
 response.getWriter() --->
 
 }
 
 }
  • MethodInterceptor(⽅法拦截器)

methodinterceptor接⼝:额外功能可以根据需要运⾏在原始⽅法执⾏ 前、后、前后。

public class Arround implements MethodInterceptor {
 /*
 invoke⽅法的作⽤:额外功能书写在invoke
 额外功能 原始⽅法之前
 原始⽅法之后
 原始⽅法执⾏之前 之后
 确定:原始⽅法怎么运⾏
 参数:MethodInvocation (Method):额外功能所增加给的那个原始⽅法
 login
 register
 invocation.proceed() ---> login运⾏
 register运⾏
 返回值:Object: 原始⽅法的返回值
 Date convert(String name)
 */
 @Override
 public Object invoke(MethodInvocation invocation) throws
Throwable {
 System.out.println("-----额外功能 log----");
 Object ret = invocation.proceed();
 return ret;
 }
}

额外功能运⾏在原始⽅法执⾏之后

@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
 Object ret = invocation.proceed();
 System.out.println("-----额外功能运⾏在原始⽅法执⾏之后----");
 return ret;
}

额外功能运⾏在原始⽅法执⾏之前,之后

什么样的额外功能 运⾏在原始⽅法执⾏之前,之后都要添加?
事务
@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
 System.out.println("-----额外功能运⾏在原始⽅法执⾏之前----");
 Object ret = invocation.proceed();
 System.out.println("-----额外功能运⾏在原始⽅法执⾏之后----");
 return ret;
}

额外功能运⾏在原始⽅法抛出异常的时候

@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
 Object ret = null;
 try {
 ret = invocation.proceed();
 } catch (Throwable throwable) {
 System.out.println("-----原始⽅法抛出异常 执⾏的额外功能 ---- ");
 throwable.printStackTrace();
 }
 return ret;
}

MethodInterceptor影响原始⽅法的返回值

原始⽅法的返回值,直接作为invoke⽅法的返回值返回,MethodInterceptor不会影
响原始⽅法的返回值
MethodInterceptor影响原始⽅法的返回值
Invoke⽅法的返回值,不要直接返回原始⽅法的运⾏结果即可。
@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
 System.out.println("------log-----");
 Object ret = invocation.proceed();
 return false;
}

以上便是本文的全部内容,我是全干程序员demo,每天为你带来最新好用的开发运维工具,如果你觉得用,请点赞,让更多的人了解相关工具

举报

相关推荐

0 条评论