手头的项目是一个外部用spring维护,内部对象全部靠new的项目,但是又用到了rpc通信,所以想出了这种折中的方案在内部去调用rpc的service
一、motan配置
根据官方文档去配置
需要做的就是要在xml中将bean配置进去
<-- 服务端-->
<!-- service implemention bean -->
<bean id="serviceImpl" class="quickstart.FooServiceImpl" />
<!-- exporting service by Motan -->
<motan:service interface="quickstart.FooService" ref="serviceImpl" export="8002" />
<-- 客户端-->
<motan:referer id="remoteService" interface="quickstart.FooService" directUrl="localhost:8002"/>
二、需要实现ApplicationContextAware接口,通过静态方法去获取bean
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
static {
ApplicationContextHolder.applicationContext = null;
}
public static ApplicationContext getApplicationContext() {
return ApplicationContextHolder.applicationContext;
}
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
ApplicationContextHolder.applicationContext = applicationContext;
}
}
三、在调用时直接使用
public class MotanClientProvider() {
public FooService getClient() {
return (FooService) ApplicationContextHolder.getApplicationContext().getBean("remoteService")
}
}
就可以返回可以使用的motan服务对象了