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>
阅读全文
0 0
- FactoryBean与动态代理结合
- 动态代理-annotation结合
- 设计模式之观察者与动态代理的结合应用
- 代理与动态代理
- jdk动态代理(动态生成字节码与反射机制的结合)
- java 动态代理 结合demo直通车
- 静态代理与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- 代理模式与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- 静态代理与动态代理
- Java 代理与动态代理
- C++指针变量的简单运算
- javascript贪吃蛇完整版
- C++ const
- String字符串去掉双引号
- lvm建立 扩容 缩小 分区取出 以及快照
- FactoryBean与动态代理结合
- git自动部署
- 方法的重载测试
- golang通过thrift链接hiveserver2
- Luogu 3865(st表)
- 算24
- 1115. Counting Nodes in a BST (30)(建立二叉搜索树)
- GUROBI 学术许可(免IP验证)申请流程
- C语言实现hashmap,安卓系统AOSP源码