dubbo的注解配置问题:dubbo的服务端service注解和spring的service、有冲突

最近在学习,dubbo。看了dubbo的xml配置后,表示好麻烦,服务端和消费端都要写一遍:类似下面的配置:(我用的spring 4.1.3.RELEASE 和dubbo2.5.3)

 

 
             

 

 

 

 

 


		
		
	 
	 
	 
	 

	 


	 
	 

	
	 

	
	
	

	
	

只有几个服务就还好,如果服务很多,估计配置文件会特别大,也不好维护。

 
所以想看看注解的写法:根据官方的教程:https://dubbo.gitbooks.io/dubbo-user-book/configuration/annotation.html
学着做了个。结果踩了很多坑,这里记录一下
 
1.服务端的把上面 
 

替换成:

 
 

然后在service的实现类名头上加:注解 @com.alibaba.dubbo.config.annotation.Service

最终结果如下:
 
 
import cn.itcast.core.dao.TestTbDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import cn.itcast.core.pojo.TestTb; /** * 测试事务 */ @Component("testTbService") @com.alibaba.dubbo.config.annotation.Service @Transactional public class TestTbServiceImpl implements TestTbService { @Autowired private TestTbDao testTbDao; @Override public void insertTestTb(TestTb testTb) { testTbDao.insertTestTb(testTb); // throw new RuntimeException(); } }

 

 

 

这里注意如果 你用的是spring的 service注解,就很容易扫包就扫不出来,服务端根本没有注册这个 service。

 

 

 

目前我踩过的坑有如下几种 dubbo不能正常注册service。
(1).用了spring的service注解:放在 dubbo的service注解上面时:     (后来再测试一遍,有莫名奇妙的可以了??)
 
@org.springframework.stereotype.Service("testTbService") @com.alibaba.dubbo.config.annotation.Service public class TestTbServiceImpl implements TestTbService {..}
 

(2).同时用了spring的事务注解 和serveice注解,这时什么顺序都不管用:。(后来再测试一遍,有莫名奇妙的可以了??)

 
 
@org.springframework.stereotype.Service("testTbService") @com.alibaba.dubbo.config.annotation.Service @Transactional 
public class TestTbServiceImpl implements TestTbService {..}

 

后来发现 用spring的 @Component注解 时这种奇怪的问题才得到解决。

 

如下:
 
 
 
@Component("testTbService") @org.springframework.stereotype.Service("testTbService") @com.alibaba.dubbo.config.annotation.Service @Transactional public class TestTbServiceImpl implements TestTbService {..}

 

 

 

 

 

2.消费端的注解配置: (ps我目前用的这个方法来配置消费端,service注入不进去,一直报service的空指针? 还是测试不通过,所以目前还是用的xml配置的方式 orz..)
 
把上面的
 
 

替换成:

 
 
 
  
 
 
然后调用时在  注入的service 成员变量头上  加上: @com.alibaba.dubbo.config.annotation.Reference

 

这里需要注意的有四点:

 

1. 此处应该扫控制器了,而不是service。
2. dubbo的扫包package的写法,他不像 spring里的扫包是  base-package,所以写完后要加上*,表示这个包里所有的内容。要不然就只扫这个包了。。
3. 一定要让dubbo的扫包在 spring的前面,要不然 会报空指针的错,因为spring先扫了控制器之后,dubbo就再也注入不进去任何值了。
4. spring的 那个自动装载注解就不需要了
 

 

你可能感兴趣的:(dubbo)