java.lang.reflect.Proxy 、java.lang.reflect.InvocationHandler
不知道怎么去解释了,如果使用Proxy 获取一个类的实例,那么在调用这个类的方法前会先执行InvocationHandler 的invoke方法,那么我们就可以利用这个特性来实现自己的AOP了,下面的例子将介绍如何实现Spring 中AOP的前通知、后通知和环绕通知。实现思路如下:
1.DynaProxy动态代理类实现接口InvocationHandler,getBean方法 返回要代理的类,(这个类必须是基于接口的),invoke方法被代理的类执行其方法前一定要调用的方法,在这个方法里面可以在控制被调用的方法是否执行,或者做点其他事情。写日志,性能计算,权限控制等,setMethodAdvice方法,绑定自己定义的通知类。
2.MethodAdvice,加载自己定义的消息通知。目前支持前通知,后通知,和环绕通知,要实现这个三个功能只需要实现对应的接口,(^_^这些接口也是我自己定义的),然后通用方法AddAdvice加载进去,这里支持多个消息通知,对于多个消息通知执行的顺序是环绕通知,前通知,后通知。
3.定义了四个接口Advice、AroundAdvice、BeforeAdvice、AfterAdvice
4.实现3个Advice的实现类,分别对应环绕通知,前通知,后通知。
5.实现自己的消息通知类MyAdvice
6.编写测试类Test
下面看具体的代码实现
- /**
- *
- */
- package com.advice;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- /**
- * @author zjb
- *
- */
- public class DynaProxy implements InvocationHandler {
- private MethodAdvice methodAdvice;
- private Object delegate;
- @Override
- public Object invoke(Object porxy, Method method, Object[] args)
- throws Throwable {
- methodAdvice.setArgs(args);
- methodAdvice.setMethod(method);
- methodAdvice.setProxy(this);
- methodAdvice.setPos(-1);
- methodAdvice.setDone(false);
- return methodAdvice.proceed();
- }
- public Object getBean(String className){
- try {
- delegate=Class.forName(className).newInstance();
- methodAdvice.setTarget(delegate);
- return Proxy.newProxyInstance(
- delegate.getClass().getClassLoader(),
- delegate.getClass().getInterfaces(), this);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- public MethodAdvice getMethodAdvice() {
- return methodAdvice;
- }
- public void setMethodAdvice(MethodAdvice methodAdvice) {
- this.methodAdvice = methodAdvice;
- }
- }
- package com.advice;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.List;
- import com.advice.impl.AfterAdviceImpl;
- import com.advice.impl.AroundAdviceImpl;
- import com.advice.impl.BeforeAdviceImpl;
- public class MethodAdvice {
- private List<Advice> adviceList=new ArrayList<Advice>();
- private Object target;
- private Method method;
- private Object[] args;
- private int pos=-1;
- private boolean done;
- private DynaProxy proxy;
- public void AddAdvice(Object [] advices){
- adviceList.clear();
- List<Advice> aroundAdvice=new ArrayList<Advice>();
- List<Advice> beforeAdvice=new ArrayList<Advice>();
- List<Advice> afterAdvice=new ArrayList<Advice>();
- for(Object o:advices){
- if (o instanceof AroundAdvice) {
- AroundAdviceImpl temp= new AroundAdviceImpl((AroundAdvice)o);
- aroundAdvice.add(temp);
- }
- if (o instanceof BeforeAdvice) {
- BeforeAdviceImpl ba= new BeforeAdviceImpl((BeforeAdvice)o);
- beforeAdvice.add(ba);
- }
- if (o instanceof AfterAdvice) {
- AfterAdviceImpl aa= new AfterAdviceImpl((AfterAdvice)o);
- afterAdvice.add(aa);
- }
- }
- adviceList.addAll(aroundAdvice);
- adviceList.addAll(beforeAdvice);
- adviceList.addAll(afterAdvice);
- }
- public Object proceed(){
- pos++;
- if(pos>=adviceList.size()&&!done){
- return invoke();
- }
- Object o=null;
- //如果执行到后通知了,那就去执行目标方法
- if(!done&& adviceList.get(pos) instanceof AfterAdvice){
- o=invoke();
- }
- adviceList.get(pos).invoke(this);
- return o;
- }
- private Object invoke(){
- done=true;
- try {
- return method.invoke(target, args);
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- public DynaProxy getProxy() {
- return proxy;
- }
- public void setProxy(DynaProxy proxy) {
- this.proxy = proxy;
- }
- public void setTarget(Object target) {
- this.target = target;
- }
- public void setArgs(Object[] args) {
- this.args = args;
- }
- public void setMethod(Method method) {
- this.method = method;
- }
- public Object getTarget() {
- return target;
- }
- public Method getMethod() {
- return method;
- }
- public Object[] getArgs() {
- return args;
- }
- public int getPos() {
- return pos;
- }
- public void setPos(int pos) {
- this.pos = pos;
- }
- public boolean isDone() {
- return done;
- }
- public void setDone(boolean done) {
- this.done = done;
- }
- }
- package com.advice;
- public interface Advice {
- public Object invoke(MethodAdvice methodAdvice) ;
- }
- package com.advice;
- public interface AroundAdvice extends Advice {
- }
- package com.advice;
- import java.lang.reflect.Method;
- public interface BeforeAdvice {
- public void before(Method m, Object[] args, Object target) ;
- }
- package com.advice;
- import java.lang.reflect.Method;
- public interface AfterAdvice {
- public void after(Method m, Object[] args, Object target) ;
- }
- package com.advice.impl;
- import com.advice.Advice;
- import com.advice.MethodAdvice;
- public class AroundAdviceImpl implements Advice {
- private Advice advice;
- @SuppressWarnings("unused")
- private AroundAdviceImpl(){};
- public AroundAdviceImpl(Advice advice){
- this.advice=advice;
- }
- @Override
- public Object invoke(MethodAdvice methodAdvice) {
- return advice.invoke(methodAdvice);
- }
- }
- package com.advice.impl;
- import com.advice.Advice;
- import com.advice.BeforeAdvice;
- import com.advice.MethodAdvice;
- public class BeforeAdviceImpl implements Advice {
- private BeforeAdvice beforeAdvice;
- @SuppressWarnings("unused")
- private BeforeAdviceImpl(){
- }
- public BeforeAdviceImpl(BeforeAdvice beforeAdvice){
- this.beforeAdvice=beforeAdvice;
- }
- @Override
- public Object invoke(MethodAdvice methodAdvice){
- beforeAdvice.before(methodAdvice.getMethod(), methodAdvice.getArgs(), methodAdvice.getTarget());
- return methodAdvice.proceed();
- }
- }
- package com.advice.impl;
- import com.advice.Advice;
- import com.advice.AfterAdvice;
- import com.advice.MethodAdvice;
- public class AfterAdviceImpl implements Advice {
- private AfterAdvice afterAdvice;
- @SuppressWarnings("unused")
- private AfterAdviceImpl(){}
- public AfterAdviceImpl(AfterAdvice afterAdvice){
- this.afterAdvice=afterAdvice;
- }
- @Override
- public Object invoke(MethodAdvice methodAdvice){
- Object retVal=methodAdvice.proceed();
- afterAdvice.after(methodAdvice.getMethod(), methodAdvice.getArgs(), methodAdvice.getTarget());
- return retVal;
- }
- }
- package com.myadvice.test;
- import java.lang.reflect.Method;
- import java.util.Arrays;
- import bsh.EvalError;
- import bsh.Interpreter;
- import com.advice.AfterAdvice;
- import com.advice.AroundAdvice;
- import com.advice.BeforeAdvice;
- import com.advice.MethodAdvice;
- public class MyAdvice implements BeforeAdvice,AfterAdvice,AroundAdvice{
- /**
- * 后通知
- */
- @Override
- public void after(Method m, Object[] args, Object target){
- System.out.println("后通知,调用的方法:"+m.getName()+",参数:"+Arrays.toString(args));
- }
- /**
- * 环绕通知,最维强大的通知,可以控制目标方法是否执行,也可以改变方法的返回值
- */
- @Override
- public Object invoke(MethodAdvice methodAdvice) {
- System.out.println("[环绕通知]");
- /**
- * 这里我们禁止李四发表任何的评论
- */
- if(methodAdvice.getMethod().getName().equals("comment")"李四".equals(methodAdvice.getArgs()[0])){
- System.out.println("屏蔽李四所有的评论");
- String returnType=methodAdvice.getMethod().getReturnType().getName();
- if("int".equals(returnType)||"long".equals(returnType)||"float".equals(returnType)||"double".equals(returnType)||"byte".equals(returnType)||"short".equals(returnType)){
- //利用BeanShell 构造一个内置变量返回,这里想了好久,没有想到什么方法可以根据
- //指定数据类型 返回指定的变量
- Interpreter i = new Interpreter();
- try {
- return i.eval("("+returnType+")0");
- } catch (EvalError e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else if("boolean".equals(returnType)){
- return false;
- }
- return null;
- }else{
- return methodAdvice.proceed();
- }
- }
- /**
- * 前通知
- */
- @Override
- public void before(Method m, Object[] args, Object target) {
- System.out.println("前通知,调用的方法:"+m.getName()+",参数:"+Arrays.toString(args));
- }
- }
- package com.myadvice.test;
- import com.advice.DynaProxy;
- import com.advice.MethodAdvice;
- import com.test.BookBiz;
- import com.test.BookBizImpl;
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- DynaProxy proxy= new DynaProxy();
- MethodAdvice methodAdvice= new MethodAdvice();
- methodAdvice.AddAdvice(new Object[]{new MyAdvice()});
- proxy.setMethodAdvice(methodAdvice);
- BookBiz bookBiz=(BookBiz)proxy.getBean(BookBizImpl.class.getName());
- bookBiz.buy("张三", "Spring深入潜出", 50);
- bookBiz.comment("李四", "《恐怖世界》一点都不恐怖,很好看!");
- bookBiz.comment("张三", "《Spring深入潜出》还是写得不错的!");
- }
- }
运行Test类得到下面的结果:
[环绕通知]
前通知,调用的方法:buy,参数:[张三, Spring深入潜出, 50.0]
业务方法buy开始执行
·张三购买图书:Spring深入潜出
·张三增加积分:5
·向物流系统下发货单
业务方法buy结束
后通知,调用的方法:buy,参数:[张三, Spring深入潜出, 50.0]
[环绕通知]
屏蔽李四所有的评论
[环绕通知]
前通知,调用的方法:comment,参数:[张三, 《Spring深入潜出》还是写得不错的!]
业务方法comment开始执行
·张三发表书评《Spring深入潜出》还是写得不错的!
业务方法comment结束
后通知,调用的方法:comment,参数:[张三, 《Spring深入潜出》还是写得不错的!]
从结果可以看出和使用spring的一样。
这个又个小小的问题,为什么spring里面前通知后通知的接口方法要包含Object object, Method method这两个参数,如果又这里两个参数那么就可以在前后通知里面去执行目标方法了,这样不是很好。还有就是使用jdk的代理,被代理的类都必须是基于接口的,重要也不是很方便,如果使用cglib动态代理类,那么被代理的类就可以不是基于接口的了,这样比较方便,下一篇将介绍如何使用cglib动态代理