1. 程式人生 > >自定義test之dubbo註解的實現

自定義test之dubbo註解的實現

       本文是作者在使用dubbo開發的時候,在使用Junit寫單元測試時,對於dubbo服務的消費者如果獲取呢,最常用就是在測試類上加註解 @ContextConfiguration("/spring-test.xml"),把需要的dubbo服務、dubbo註冊中心(如果有)、通訊協議配置在spring-test.xml中,則可以像本地服務一樣使用dubbo服務,啟動的時候會啟動spring容器。這樣方式的麻煩點在spring-test的配置,有時候會比較頭痛,今天作者提供一種零配置+註解的方式使用dubbo服務的方式,下面是簡單的實現。 首先編寫一個註解類,InjectionDubbo:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface InjectionDubbo { String registryAddress() default "192.168.0.61:2181"; }
其中,registryAddress是註冊中心的地址。 下面編寫dubbo監聽類,InjectionDubboListener :
import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.ReferenceConfig; import com.alibaba.dubbo.config.RegistryConfig; import org.apache.commons.lang3.StringUtils; import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; import java.lang.reflect.Field; public class InjectionDubboListener implements TestExecutionListener { @Override public void beforeTestClass(TestContext testContext) throws Exception {}
//初始化dubbo @Override public void prepareTestInstance(TestContext testContext) throws Exception { Class clzss = testContext.getTestClass(); Field[] fields=clzss.getDeclaredFields(); for(Field field:fields){ if(field.isAnnotationPresent(InjectionDubbo.class)){ InjectionDubbo dubboAnnotation=field.getAnnotation(InjectionDubbo.class); if(dubboAnnotation != null){ field.setAccessible(true); field.set(testContext.getTestInstance(),initService(dubboAnnotation.registryAddress(),field.getType())); } } } } @Override public void beforeTestMethod(TestContext testContext) throws Exception { }
@Override public void afterTestMethod(TestContext testContext) throws Exception { } @Override public void afterTestClass(TestContext testContext) throws Exception { } private Object initService(String registryAddress, Class cla){ //當前應用配置 ApplicationConfig application= new ApplicationConfig(); application.setName("dubboName"); // 連線註冊中心配置 RegistryConfig registry=new RegistryConfig(); if(StringUtils.isNotBlank(registryAddress)){ registry.setAddress(registryAddress); }else{ registry.setAddress("192.168.0.61:2181"); } //引用遠端服務 ReferenceConfig<Object> reference=new ReferenceConfig<Object>(); reference.setApplication(application); reference.setRegistry(registry); reference.setInterface(cla); //和本地一樣使用服務 return reference.get(); } }
監聽器實現TestExecutionListener,重寫它的prepareTestInstance方法,方法中查詢所有添加了InjectionDubbo註解的屬性,使用反射例項化該屬性的dubbo服務。 至此則算完成了。是不是簡短的幾行程式碼。 使用的時候則只需要在測試的屬性欄位上增加InjectionDubbo註解即可。 上面的工作是把原來的測試類的使用方式從
在測試類上加 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring-test.xml") 在dubbo服務屬性上加@Autowired
過度到
在測試類上加 @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({InjectionDubboListener .class}) 在dubbo服務屬性上加@InjectionDubbo
這樣好處是不用再每增加一個dubbo服務總是要在spring-test.xml加對應的reference,適合懶人的小工具。