FactoryBean与动态代理结合

来源:互联网 发布:私密空间软件 编辑:程序博客网 时间:2024/05/22 11:03

FactoryBean

  与普通Bean区别: FactoryBean返回的对象不是其实现类的一个实例,而是getObject()方法所返回的对象。
  作用: bean的配置统一, 控制getObject()的逻辑返回不同的bean;

与动态代理结合

  场景: RPC调用时,消费者需要向调用本地服务一样调用远程服务,这就需要对消费者进行代理,将远程服务调用过程封装,使得调用方不感知。

代码示例

/** * 类描述:远程服务接口 *  * @author ruipeng.lrp * @since 2017/11/7 **/public interface RemoteService {    void print(String data);}
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import org.springframework.beans.factory.FactoryBean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * 类描述:远程服务消费者代理工厂bean *  * @author ruipeng.lrp * @since 2017/11/7 **/public class RpcConsumerProxyFactoryBean implements FactoryBean {    //代理的接口名    private String interfaceName;    /**     * 类描述:代理类处理逻辑     **/    class InvocationHandlerImpl implements InvocationHandler {        @Override        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {            // RPC调用            System.out.println("RPC调用: " + method.getName());            return null;        }    }    @Override    public Object getObject() throws Exception {        Object proxy = Proxy.newProxyInstance(RpcConsumerProxyFactoryBean.class.getClassLoader(),                new Class[] { getObjectType() }, new InvocationHandlerImpl());        return proxy;    }    @Override    public Class getObjectType() {        try {            return Class.forName(interfaceName);        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        return null;    }    public String getInterfaceName() {        return interfaceName;    }    public void setInterfaceName(String interfaceName) {        this.interfaceName = interfaceName;    }    public static void main(String[] args) throws Exception {        ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");        RemoteService remoteService = (RemoteService) context.getBean("remoteService");        remoteService.print("langxie");    }}
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    <bean id="remoteService" class="proxy.RpcConsumerProxyFactoryBean">        <property name="interfaceName">            <value>proxy.RemoteService</value>        </property>    </bean></beans>
原创粉丝点击