本文主要是介绍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>
这篇关于FactoryBean与动态代理结合的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!