鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ Dubbo+SpringBoot整合: 依賴注入Null Pointer Exc

Dubbo+SpringBoot整合: 依賴注入Null Pointer Exception的問題

我用Dubbo+SpringBoot搭建微服務(wù)
controller和service分別屬于兩個服務(wù)
里面分別有如下類

@RestController
@RequestMapping("product")
public class ProductController{

    @Reference(version="1.0.0")
    ProductService productService;
    
    @GetMapping("create")
    public String createProduct(){
        return productService.createProduct();
    }
}


@Component
@Service(version = "1.0.0")
public class ProductServiceImpl implements ProductService {
   @Override
    public String createProduct(){
        return "created";
    }
}

我發(fā)現(xiàn)如果我先啟動service服務(wù),后啟動controller服務(wù),運行OK
但是如果我先啟動controller服務(wù),后啟動service服務(wù),productService就是null,出現(xiàn)Null Pointer Exception

我的理解是:因為service后啟動,所以controller中的productService依賴注入時找不到實例,注入失敗。
但是這樣的話,那假如有兩個service微服務(wù),A和B,A中的某個類需要B中某個類的服務(wù),而B中某個類又需要A中某個類的服務(wù),那誰先啟動都會有問題啊。
怎么回事?

回答
編輯回答
尛曖昧
  1. 建議你在細看一下Dubbo文檔,并找一些示例看一下
  2. 關(guān)于Reference,建議你單獨新建一個文件夾 將Reference 獨立出來,避免重復(fù)寫Reference(version="1.0.0") 等信息
  3. Dubbo是有服務(wù)注冊與發(fā)現(xiàn)的。假如A依賴B,A先啟動,B后啟動。①可以設(shè)置A中對B的依賴 check=false 不進行檢查 ②B啟動時,會給所有已訂閱該服務(wù)的系統(tǒng)進行推送/通知~ (其實還是1.的問題,多看文檔)
2017年3月25日 18:53
編輯回答
莓森

dubbo=2.6.1

        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
//消費時
    @Reference(version="0.0.1", timeout = 5000, check= false)
    private HelloWorldService helloWorldService;
// 啟動類
@SpringBootApplication
@EnableDubboConfiguration
@EnableAspectJAutoProxy

服務(wù)提供方

@Service(version = "0.0.1", timeout = 5000, interfaceClass = HelloWorldService.class)
public class HelloWorldServiceImpl implements HelloWorldService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /*
     * (non-Javadoc)
     * 
     * @see org.bjhxxt.shop.service.HelloWorldService#sayHello(java.lang.String)
     */
    @Override
    public String sayHello(String name) {
        logger.debug("hello dubbo service");
        return "Hello dubbo for " + name;
    }

}

親測是可以的,當(dāng)然除了上面的如果有漏掉的,就不一定了。

2017年12月4日 13:28
編輯回答
莓森

spring mvc注解和 dubbo注解配置在兩個不同的context導(dǎo)致的
比較簡單的解決辦法是不要在controller里使用dubbo注解

2018年2月6日 17:32