》 config.properties 配置文件 key=类名
》 BeanFactory Bean工厂,负责得到bean getBean(“xxx”)
》ProxyBeanFactory 产生代理的工厂 getProxy(Object target,Advice advice);
》AopFrameworkTest 测试类
思路:
getBean(”xxx”)
xxx=ProxyBeanFactory 时,返回代理类对象
xxx=其他类时,直接返回该类对象
- config.properties
#xxx=java.util.ArrayList xxx=com.itcast.day3.aopframework.ProxyBeanFactory xxx.advice=com.itcast.day3.MyAdvice xxx.target=java.util.ArrayList
- BeanFactory
package com.itcast.day3.aopframework; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import com.itcast.day3.Advice; public class BeanFactory { private Properties props=new Properties(); public BeanFactory(InputStream ips){ try { props.load(ips); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //bean工厂 public Object getBean(String name){ Object bean=null; try { bean=Class.forName(props.getProperty(name)).newInstance(); if(bean instanceof ProxyBeanFactory){ Object proxy=null; ProxyBeanFactory proxyFactoryBean=(ProxyBeanFactory)bean; Advice advice = (Advice)Class.forName(props.getProperty(name+".advice")).newInstance(); Object target = Class.forName(props.getProperty(name+".target").newInstance()); proxyFactoryBean.setAdvice(advice); proxyFactoryBean.setTarget(target); proxy=proxyFactoryBean.getProxy(); return proxy; } } catch (Exception e) { e.printStackTrace(); } return bean; } }
- ProxyBeanFactory
package com.itcast.day3.aopframework; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import com.itcast.day3.Advice; public class ProxyBeanFactory { private Advice advice;//系统功能的封装,一般都有一个接口 private Object target;//目标类 public Advice getAdvice() { return advice; } public void setAdvice(Advice advice) { this.advice = advice; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } public Object getProxy() { Object proxy = Proxy.newProxyInstance( target.getClass().getClassLoader(), //目标类的类加载器 target.getClass().getInterfaces(), //目标类实现的接口 new InvocationHandler(){//匿名内部类 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { advice.beforeMethod(method); Object reVal=method.invoke(target, args);//反射方式调用目标类的方法 advice.afterMethod(method); return reVal; } } ); return proxy; } }
- AopFrameworkTest
开始做,坚持做,重复做package com.itcast.day3.aopframework; import java.io.InputStream; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; public class AopFrameworkTest { public static void main(String[] args) throws Exception { InputStream ips=AopFrameworkTest.class.getResourceAsStream("config.properties"); Object bean=new BeanFactory(ips).getBean("xxx"); if(bean instanceof ArrayList){ Collection collection=((Collection)bean); collection.add("123"); for(Object obj:collection){ System.out.println(obj); } }else{ System.out.println("返回的是代理类: "+bean.getClass().getName()+" 的实例"); ((Collection)bean).clear(); } } }