A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Bule丶 中级黑马   /  2014-8-3 00:09  /  972 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Bule丶 于 2014-8-3 00:19 编辑

BeanFactory:--------------------------   

package com.hans.aopframework;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.hans.myproxy.Advice;

public class BeanFactory {

Properties properties = new Properties();

public BeanFactory(InputStream ips){
  try {
   properties.load(ips);
  } catch (IOException e) {
   e.printStackTrace();
  }
}

public Object getBean(String name){
  String className = properties.getProperty(name); //得到类名
  Object bean = null;
  try {
   Class clazzBean = Class.forName(className); //反射得到类
   bean = clazzBean.newInstance();
  } catch (Exception e) {
   e.printStackTrace();
  }
   
  if(bean instanceof ProxyBeanFactory){ //如果此类是个代理类
   Object proxy = null;
   ProxyBeanFactory proxyBeanFactory = (ProxyBeanFactory)bean; //强转代理对象
   try {
    Advice advice = (Advice) Class.forName(properties.getProperty(name + ".advice")).newInstance(); //得到建议
    Object target = Class.forName(properties.getProperty(name + ".target")).newInstance(); //得到目标
    proxyBeanFactory.setAdvice(advice);
    proxyBeanFactory.setTarget(target);
    proxy = proxyBeanFactory.getProxy(); //创建代理
   } catch (Exception e) {
    e.printStackTrace();
   }
   
  }
  return bean;
}


}










ProxyBeanFactory:--------------  负责创建代理

package com.hans.aopframework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.hans.myproxy.Advice;

public class ProxyBeanFactory {

private static Object target;
private static Advice advice;

public static Object getTarget() {
  return target;
}

public static void setTarget(Object target) {
  ProxyBeanFactory.target = target;
}

public static Advice getAdvice() {
  return advice;
}

public static void setAdvice(Advice advice) {
  ProxyBeanFactory.advice = advice;
}

public static Object getProxy() {
  return Proxy.newProxyInstance(target.getClass().getClassLoader(),
    target.getClass().getInterfaces(), new InvocationHandler() {

     @Override
     public Object invoke(Object proxy, Method method,
       Object[] args) throws Throwable {
      advice.content1(method);
      Object retObje = method.invoke(target, args);
      advice.content2(method);
      return retObje;
     }
    });
}

}





测试类:----------------------

package com.hans.aopframework;

import java.io.InputStream;

public class BeanFactoryTest {

/**
  * @param args
  */
public static void main(String[] args) {
  try {
   InputStream ips = BeanFactoryTest.class.getResourceAsStream("config.properties");
   Object f = new BeanFactory(ips).getBean("xxx");
   System.out.println(f.getClass().getName());
  } catch (Exception e) {
   e.printStackTrace();
  }
}

}


晚上看了一晚上,都看完了

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马