FactoryBean与动态代理结合

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

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

代码示例
// 类描述:远程服务接
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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值