dubbo支持注解配置,<dubbo:annotation />,注解配置给人的感觉就是比较省事,但是对于dubbo却并不适用。
provider,使用dubbo自定义的@Service注解,使用<dubbo:annotation/>代替<context:component-scan>
consumer,dubbo会处理spring上下文中bean里面的@Reference引用,注入远程调用代理对象
如果满足于此,则dubbo的注解配置还是很省事的,在实现类上注解@Service,在服务类里引入@Reference。唯一的突出问题是:代码与dubbo耦合得太紧了!
代码里面可以没有任何dubbo类(使用spring通用的@Service和@Autowired),
运行时可以配置dubbo也可以配置单机(本机测试开发时可以不用dubbo,直接加载全部repository和service类就行了),
<dubbo:reference>配置更方便配置其他性能参数(甚至方法级别的配置参数)
按需配置,接口多时会麻烦一点,然而微调每个接口参数时就会方便很多了
dubbo也可以实现自己的ApplicationContext,当注入@Autowired或@Resource找不到bean时,自动从注册中心获取远程调用对象引用并向spring注册bean。
provider,使用dubbo自定义的@Service注解,使用<dubbo:annotation/>代替<context:component-scan>
import com.alibaba.dubbo.config.annotation.Service;
@Service
public class FooServiceImpl implements FooService {
public String foo(String foo) {
return "Foo: "+foo;
}
}
<dubbo:application name="ite-provider" />
<dubbo:registry address="redis://127.0.0.1:6379"/>
<dubbo:annotation package="com.itecheast.ite.domain.impl.test"/>
<!-- 还是可以使用component-scan,添加对应的filter即可
<dubbo:annotation/>
<context:component-scan base-package="com.itecheast.ite.domain.impl.test">
<context:include-filter type="annotation" expression="com.alibaba.dubbo.config.annotation.Service"/>
</context:component-scan> -->
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:provider.xml" })
public class Provider {
@Test
public void provide() throws IOException {
System.in.read();
System.out.println("Provider Exit");
}
}
consumer,dubbo会处理spring上下文中bean里面的@Reference引用,注入远程调用代理对象
public interface FooService {
String foo(String foo);
}
import com.alibaba.dubbo.config.annotation.Reference;
@Component
public class BarAction {
@Reference FooService fooService; //dubbo会处理此注解
public void bar() {
System.out.println(fooService.foo("foo"));
}
}
<dubbo:application name="ite-consumer" />
<dubbo:registry address="redis://127.0.0.1:6379"/>
<dubbo:annotation package="com.itecheast.ite.domain.impl.action"/>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:consumer.xml" })
public class Consumer {
@Autowired BarAction barAction;//这里使用@Reference FooService会报错,dubbo处理bean里面的注解,而Consumer没有被处理
@Test public void bar() {
barAction.bar();
}
}
如果满足于此,则dubbo的注解配置还是很省事的,在实现类上注解@Service,在服务类里引入@Reference。唯一的突出问题是:代码与dubbo耦合得太紧了!
代码里面可以没有任何dubbo类(使用spring通用的@Service和@Autowired),
运行时可以配置dubbo也可以配置单机(本机测试开发时可以不用dubbo,直接加载全部repository和service类就行了),
<dubbo:reference>配置更方便配置其他性能参数(甚至方法级别的配置参数)
按需配置,接口多时会麻烦一点,然而微调每个接口参数时就会方便很多了
<!-- fooService是spring上下文的一个bean,按FooService接口发布到注册中心 -->
<dubbo:service ref="fooService" interface="com.itecheast.ite.domain.impl.test.FooService" />
<!-- 从注册中心订阅FooService的实现,并注册为spring上下文的名为fooService的bean,从而支持@Autowired注入 -->
<dubbo:reference id="fooService" interface="com.itecheast.ite.domain.impl.test.FooService" />
dubbo也可以实现自己的ApplicationContext,当注入@Autowired或@Resource找不到bean时,自动从注册中心获取远程调用对象引用并向spring注册bean。