- 修改相应的dubbo.properties,启动com.alibaba.dubbo.demo.provider.DemoProvider作为服务提供方。
- 修改相应的dubbo.properties,调试com.alibaba.dubbo.demo.consumer.DemoConsumer作为服务引用方。
1、 consumer端服务引用配置
1.1、服务提接口pom坐标
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo-demo-api</artifactId>
<version>${project.parent.version}</version>
</dependency>
1.2、dubbo:reference标签
基于dubbo.xsd中描述的扩展spring schema类配置xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="demo-consumer"/>
<!-- 使用multicast广播注册中心暴露发现服务地址 -->
<!--<dubbo:registry address="multicast://224.5.6.7:1234"/>-->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="demoService" check="false" interface="com.alibaba.dubbo.demo.DemoService"/>
<bean class="com.alibaba.dubbo.demo.consumer.DemoAction" init-method="start">
<property name="demoService" ref="demoService"/>
</bean>
</beans>
1.3、注入代码
通过set的方式来注入DemoService属性【spring Ioc的一种注入方式】
public class DemoAction {
private DemoService demoService;
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
...
}
2、问题
这一些列操作完了,在conusmer端,我们并没有看到DemoService的任何实现类。那么问题来了,
2.1、如何获得DemoService实例的
从https://segmentfault.com/a/11...,我们可以类比得知,dubbo:reference会映射成一个ReferenceBean
public class ReferenceBean<T> extends ReferenceConfig<T> implements FactoryBean, ApplicationContextAware, InitializingBean, DisposableBean {
private static final long serialVersionUID = 213195494150089726L;
private transient ApplicationContext applicationContext;
public ReferenceBean() {
super();
}
...
public Object getObject() throws Exception {
return get();
}
public Class<?> getObjectType() {
return getInterfaceClass();
}
@Parameter(excluded = true)
public boolean isSingleton() {
return true;
}
...
}
发现ReferenceBean实现了FactoryBean接口,FactoryBean是一个Java Bean,但是它是一个能生产对象的工厂Bean。通过FactoryBean#getObject我们就可以拿到该对象的实例。
public interface FactoryBean<T> {
//返回由FactoryBean创建的bean实例,如果isSingleton()返回true,则该实例会放到Spring容器中单实例缓存池中。
T getObject() throws Exception;
//返回FactoryBean创建的bean类型。
Class<?> getObjectType();
//返回由FactoryBean创建的bean实例的作用域是singleton还是prototype。
boolean isSingleton();
}
2.2、获得的DemoService实例是啥
那么FactoryBean#getObject到底都发生了啥,下面我们来粗略的看一下。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。