下面是实现Spring中AOP的代码的原理:
1.工厂类BeanFactory负责创建目标类或代理类得实例对象并通过配置文件实现切换。其getBean()方法根据参数字符串返回一个相应的实例对象,如果参数字符串在配置文件中对应的类名不是ProxyFactoryBean,则直接返回该类的实例对象,否则,返回该类实例对象的getProxy()方法返回的对象。我们在使用Spriing时,就是用这个类来获取我们要的对象实例。代码如下:
public class BeanFactory {
  Properties props = new Properties();
  public BeanFactory(InputStream is) {
   try {
    props.load(is);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  }
  
  public Object getBean(String name) {
  String className = props.getProperty(name);
   Object bean = null;
   try {
    Class clazz = Class.forName(className);
    bean = clazz.newInstance();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
     if(bean instanceof ProxyFactoryBean) {
    Object proxy = null;
    ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
    try {
     Object target = Class.forName(props.getProperty(name + ".target")).newInstance();
     Advice advice = (Advice)Class.forName(props.getProperty(name + ".advice")).newInstance();
     proxyFactoryBean.setTarget(target);
     proxyFactoryBean.setAdvice(advice);
     proxy = proxyFactoryBean.getProxy();
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
   return proxy;
  }
  return bean;
 }
 }
 2.ProxyFactoryBean充当封装生成动态代理的工厂,需要为工厂类提高那个哪些配置参数信息?(目标、通知)
public class ProxyFactoryBean {
 private Advice advice;
 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;
 }
 private Object target;
 public Object getProxy() {
 Object proxy=Proxy.newProxyInstance(
 target.getClass().getClassLoader(),
 /*new Class[]{target.getClass()},*/
 target.getClass().getInterfaces(),
 new InvocationHandler() {
 @Override
 public Object invoke(Object proxy, Method method, Object[] args)
 throws Throwable {
 advice.beforeMethod(method);
 Object retVal=method.invoke(target, args);
 advice.afterMethod(method);
 return retVal;
 }
 });
 return proxy;
 }
 }3.Advice接口,我们要给目标类加功能时,就要创建实现这个接口的类, 当然这个接口中还有其他方法签名
public interface Advice {
 void beforeMethod(Method method); //i
 void afterMethod(Method method);
 }







