在上篇筆記《<context:component-scan> 配置 —— 分庫遇到問題(1)》中解決了 spring中某些實(shí)例被初始化了兩次的問題,
但是緊接著又來了另一個(gè)頭疼的問題,dubbo的@Reference為null無法注入 !
Controller層的注解正常?。?/p>
<dubbo:annotation />
<context:component-scan base-package="xxx" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController" />
</context:component-scan>
我把這個(gè)問題提出來之后,大家都提出來,在dubbo的service或者spring還沒有初始化完成之前就開始掃描 @Reference導(dǎo)致取到null值。但是怎么去找到問題的根源呢?
于是幾個(gè)人在一塊排查,剛開始是修改spring的配置文件。把有關(guān)掃描的配置重新檢查了一下,并沒有發(fā)現(xiàn)問題。網(wǎng)上查關(guān)于dubbo初始化的資料,依然沒有發(fā)現(xiàn)解決問題的方法!
查詢無果后,開始往源碼上面去研究。
我始終在想,之前dubbo使用沒有問題的,就在我昨天加了use-default-filters="false"才出現(xiàn)的這個(gè)問題,所以我圍繞著 context:component-scan + dubbo:annotation尋找答案,其中一條結(jié)果是指向 Dubbo的官方文檔。如下:
服務(wù)提供方注解:
import com.alibaba.dubbo.config.annotation.Service;
@Service(version="1.0.0")
public class FooServiceImpl implements FooService {
}
服務(wù)提供方配置:
<!-- 公共信息,也可以用dubbo.properties配置 -->
<dubbo:application name="annotation-provider" />
<dubbo:registry address="127.0.0.1:4548" />
<!-- 掃描注解包路徑,多個(gè)包用逗號(hào)分隔,不填pacakge表示掃描當(dāng)前ApplicationContext中所有的類 -->
<dubbo:annotation package="com.foo.bar.service" />
服務(wù)消費(fèi)方注解:
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
@Component
public class BarAction {
@Reference(version="1.0.0")
private FooService fooService;
}
服務(wù)消費(fèi)方配置:
<!-- 公共信息,也可以用dubbo.properties配置 -->
<dubbo:application name="annotation-consumer" />
<dubbo:registry address="127.0.0.1:4548" />
<!-- 掃描注解包路徑,多個(gè)包用逗號(hào)分隔,不填pacakge表示掃描當(dāng)前ApplicationContext中所有的類 -->
<dubbo:annotation package="com.foo.bar.action" />
也可以使用:(等價(jià)于前面的:<dubbo:annotation package="com.foo.bar.service" />)
<dubbo:annotation />
<context:component-scan base-package="com.foo.bar.service">
<context:include-filter type="annotation" expression="com.alibaba.dubbo.config.annotation.Service" />
</context:component-scan>
從官方給的樣例找到了問題產(chǎn)生的原因。dubbo:annotation不指定包名的話會(huì)在spring bean中查找對(duì)應(yīng)實(shí)例的類配置了dubbo注解的。