简单接口HelloService
public interface HelloService {
public void sayHello(String name);
}
实现类HelloServiceImpl
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello(String name) {
if (name == null || name.trim() == null) {
throw new RuntimeException("Parameter is null!!");
}
System.out.println("hello " + name);
}
}
定义拦截器接口
package com.springboot.chapter4.intercept;
import com.springboot.chapter4.invoke.Invocation;
public interface Interceptor {
public boolean before();
public void after();
public Object around(Invocation invocation) throws Throwable;
public void afterReturning();
public void afterThrowing();
boolean useAround();
}
around方法中的参数Invocation对象
package com.springboot.chapter4.invoke;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Invocation {
private Object[] params;
private Method method;
private Object target;
public Invocation(Object target, Method method, Object[] params) {
this.target = target;
this.method = method;
this.params = params;
}
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, params);
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
}
根据拦截器接口的定义开发属于自己的拦截器MyInterceptor
package com.springboot.chapter4.intercept;
import org.aopalliance.intercept.Invocation;
public class MyInterceptor implements Interceptor {
@Override
public boolean before() {
System.out.println("before……");
return true;
}
@Override
public void after() {
System.out.println("after……");
}
@Override
public Object around(com.springboot.chapter4.invoke.Invocation invocation) throws Throwable {
System.out.println("around before……");
Object obj = invocation.proceed();
System.out.println("around after……");
return null;
}
@Override
public void afterReturning() {
System.out.println("afterReturning……");
}
@Override
public void afterThrowing() {
System.out.println("afterThrowing……");
}
@Override
public boolean useAround() {
return true;
}
}
测试约定流程
private static void testProxy() {
HelloService helloService = new HelloServiceImpl();
HelloService proxy = (HelloService) ProxyBean.getProxyBean(helloService, new MyInterceptor());
proxy.sayHello("zhangsan");
System.out.println("\n#############name is null!!#############\n");
proxy.sayHello(null);
}
按照约定,这段代码打印的结果如下
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)