本帖最后由 aspoMAN 于 2013-9-22 10:07 编辑
- import java.io.*;
- import java.util.Properties;
- public class BeanFactory {
- //配置文件存储对象
- Properties props = new Properties();
- public BeanFactory(InputStream ips){
- try {
- props.load(ips);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- //getBean方法
- public Object getBean(String name) throws Exception {
- //从配置文件获取要创建的Bean名
- String className = props.getProperty(name);
-
- Object bean = null;
-
- try {
- //根据className得到相应的class对象
- Class clazz = Class.forName(className);
-
- //对象实例化
- bean = clazz.newInstance();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- //判断如果传入的bean为ProxyFactoryBean的实例化对象,则创建代理进行处理,否则返回bean
- if(bean instanceof ProxyFactoryBean){
- ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
- //通过配置文件获得Advice实例对象、target对象
- 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);
- Object proxy = proxyFactoryBean.getProxy(proxyFactoryBean,advice);
- return proxy;
- }
- return bean;
- }
- }
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- public class ProxyFactoryBean {
- 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;
- }
- //获得Proxy对象
- public Object getProxy(final Object target,final Advice advice) {
- //传递三个参数创建一个proxy对象
- Object proxy1 = 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 retValue = method.invoke(target, args);
- advice.afterMethod(method);
-
- return retValue;
- }
- }
- );
- return proxy1;
- }
-
- }
复制代码 BeanFactory 和 ProxyFactoryBean类
|