Spring ProxyFactory 和 方法拦截器 MethodInterceptor
所属分类 spring
浏览量 530
ProxyFactory proxyFactory=new ProxyFactory();
proxyFactory.setTarget(new Hello());
proxyFactory.addAdvice(new HelloMethodInterceptor());
Hello hello = (Hello) proxyFactory.getProxy();
target 被代理对象 Hello
方法拦截器 HelloMethodInterceptor
public class Hello{
public String hello(String name) {
if(name==null) {
throw new RuntimeException("name is null");
}
return "hello,"+name;
}
public String hello2(String name) {
if(name==null) {
throw new RuntimeException("name is null");
}
return "hello2,"+name;
}
}
HelloMethodInterceptor
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class HelloMethodInterceptor implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object result=null;
try{
System.out.println("method="+methodInvocation.getMethod());
System.out.println("args="+methodInvocation.getArguments());
result= methodInvocation.proceed();
return result;
}catch (Exception e){
System.out.println("invoke error,"+e);
return result;
}
}
}
测试类 Main.java
import org.springframework.aop.framework.ProxyFactory;
public class Main{
public static void main(String[] args)throws Exception {
ProxyFactory proxyFactory=new ProxyFactory();
proxyFactory.setTarget(new Hello());
proxyFactory.addAdvice(new HelloMethodInterceptor());
Hello hello = (Hello) proxyFactory.getProxy();
System.out.println(hello.getClass());
System.out.println(hello.toString());
System.out.println(hello.hashCode());
System.out.println(hello.hello(null));
System.out.println(hello.hello("dyyx"));
System.out.println(hello.hello2("dyyx"));
}
}
完整代码
https://gitee.com/dyyx/hellocode/tree/master/demo/springbootdemo/src/main/java/proxyfactory
代理的几种实现方式
基于Aspect注解的spring aop 实例
AOP要点整理
AspectJ简介及实例
spring aop 内部方法调用拦截说明
spring aop cglib 代理类源码查看
上一篇
下一篇
dubbo简史
Dubbo2.7三大新特性简介
zookeeper单机安装
Spring AOP @Aspect
powermock 静态方法mock
mockito 实例