注解配置

以注解配置的方式来配置你的 Dubbo 应用

提示

需要 2.6.3 及以上版本支持。 点此查看 完整示例

服务提供方

Service注解暴露服务

  1. @Service
  2. public class AnnotationServiceImpl implements AnnotationService {
  3. @Override
  4. public String sayHello(String name) {
  5. return "annotation: hello, " + name;
  6. }
  7. }

增加应用共享配置

  1. # dubbo-provider.properties
  2. dubbo.application.name=annotation-provider
  3. dubbo.registry.address=zookeeper://127.0.0.1:2181
  4. dubbo.protocol.name=dubbo
  5. dubbo.protocol.port=20880

指定Spring扫描路径

  1. @Configuration
  2. @EnableDubbo(scanBasePackages = "org.apache.dubbo.samples.simple.annotation.impl")
  3. @PropertySource("classpath:/spring/dubbo-provider.properties")
  4. static public class ProviderConfiguration {
  5. }

服务消费方

Reference注解引用服务

  1. @Component("annotationAction")
  2. public class AnnotationAction {
  3. @Reference
  4. private AnnotationService annotationService;
  5. public String doSayHello(String name) {
  6. return annotationService.sayHello(name);
  7. }
  8. }

增加应用共享配置

  1. # dubbo-consumer.properties
  2. dubbo.application.name=annotation-consumer
  3. dubbo.registry.address=zookeeper://127.0.0.1:2181
  4. dubbo.consumer.timeout=3000

指定Spring扫描路径

  1. @Configuration
  2. @EnableDubbo(scanBasePackages = "org.apache.dubbo.samples.simple.annotation.action")
  3. @PropertySource("classpath:/spring/dubbo-consumer.properties")
  4. @ComponentScan(value = {"org.apache.dubbo.samples.simple.annotation.action"})
  5. static public class ConsumerConfiguration {
  6. }

调用服务

  1. public static void main(String[] args) throws Exception {
  2. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
  3. context.start();
  4. final AnnotationAction annotationAction = (AnnotationAction) context.getBean("annotationAction");
  5. String hello = annotationAction.doSayHello("world");
  6. }

最后修改 September 21, 2021: Bug fix miss mialbox (#953) (57cf51b)