注解配置

需要 2.5.7 及以上版本支持

服务提供方

Service注解暴露服务

  1. import com.alibaba.dubbo.config.annotation.Service;
  2. @Service(timeout = 5000)
  3. public class AnnotateServiceImpl implements AnnotateService {
  4. // ...
  5. }

javaconfig形式配置公共模块

  1. @Configuration
  2. public class DubboConfiguration {
  3. @Bean
  4. public ApplicationConfig applicationConfig() {
  5. ApplicationConfig applicationConfig = new ApplicationConfig();
  6. applicationConfig.setName("provider-test");
  7. return applicationConfig;
  8. }
  9. @Bean
  10. public RegistryConfig registryConfig() {
  11. RegistryConfig registryConfig = new RegistryConfig();
  12. registryConfig.setAddress("zookeeper://127.0.0.1:2181");
  13. registryConfig.setClient("curator");
  14. return registryConfig;
  15. }
  16. }

指定dubbo扫描路径

  1. @SpringBootApplication
  2. @DubboComponentScan(basePackages = "com.alibaba.dubbo.test.service.impl")
  3. public class ProviderTestApp {
  4. // ...
  5. }

服务消费方

Reference注解引用服务

  1. public class AnnotationConsumeService {
  2. @com.alibaba.dubbo.config.annotation.Reference
  3. public AnnotateService annotateService;
  4. // ...
  5. }

javaconfig形式配置公共模块

  1. @Configuration
  2. public class DubboConfiguration {
  3. @Bean
  4. public ApplicationConfig applicationConfig() {
  5. ApplicationConfig applicationConfig = new ApplicationConfig();
  6. applicationConfig.setName("consumer-test");
  7. return applicationConfig;
  8. }
  9. @Bean
  10. public ConsumerConfig consumerConfig() {
  11. ConsumerConfig consumerConfig = new ConsumerConfig();
  12. consumerConfig.setTimeout(3000);
  13. return consumerConfig;
  14. }
  15. @Bean
  16. public RegistryConfig registryConfig() {
  17. RegistryConfig registryConfig = new RegistryConfig();
  18. registryConfig.setAddress("zookeeper://127.0.0.1:2181");
  19. registryConfig.setClient("curator");
  20. return registryConfig;
  21. }
  22. }

指定dubbo扫描路径

  1. @SpringBootApplication
  2. @DubboComponentScan(basePackages = "com.alibaba.dubbo.test.service")
  3. public class ConsumerTestApp {
  4. // ...
  5. }

注意

如果你曾使用旧版annotation配置,请删除所有相关配置,我们将在下个版本删除所有旧版配置项。

  1. <dubbo:annotation package="com.alibaba.dubbo.test.service" />

原文: http://dubbo.apache.org/#!/docs/user/configuration/annotation.md?lang=zh-cn