天天看點

maven項目多子產品互相調用方法問題背景解決方法

maven項目多子產品互相調用方法

  • 問題背景
  • 解決方法
    • 方法1
    • 方法2

問題背景

maven項目包括多個子子產品,類似下圖:

maven項目多子產品互相調用方法問題背景解決方法

現在【web】子產品某個類想要調用【service】子產品的某個類的某個方法。

如果直接通過@Autowired注入【service】子產品的某個類,會發現編譯器根本找不到那個類,因為跨子產品了。

解決方法

方法1

在【web】子產品的pom.xml中添加依賴,引入【service】子產品,類似:

<dependency>
    <groupId>com.***.***</groupId>
    <artifactId>service</artifactId>
</dependency>
           

添加完重新整理maven,然後就能在【web】子產品中注入【service】子產品的類了。

方法2

方法1通常情況下就能解決問題,但是若之前【service】子產品已經引入了【web】子產品,此時再根據方法1在【web】中引入【service】的話,就會出現循環依賴,啟動報錯。

此時可以采用直接調用接口的方法:

假如我們在【web】子產品中想調用的就是【service】子產品中的"check"方法(如下),我們無法像方法1中直接調用check方法時,可以選擇直接調用“api/v1/bbb/aaa”這個接口來達到目的

@GetMapping("api/v1/bbb/aaa")
@ResponseBody
public void getCheck(@RequestParam Map<String,String> map){
    String ttt= JSONObject.toJSONString(map);
    check(ttt);
}
           

直接調用接口的步驟:

  • 定義接口位址(不這麼定義,調用時直接寫也行)
public String getURL(){
    //port是通路端口号,***是通路的context-path,自己調整吧
    return "http://127.0.0.1:" + port + "/***/api/v1/bbb/aaa";
}
           

大家應該注意到上述接口位址并沒帶參數,是以還需要寫一個工具類用來拼接請求參數。

這個是get請求,是以工具類如下:

public Object sendGetRequest(String url, Map<String, String> requestLine)
            throws HttpResponseOfInterfaceException {
        HttpURLConnection httpConn = null;
        InputStreamReader inpRead = null;
        BufferedReader inputStreamOfHttpRsp = null;
        try {
            StringBuilder requestUrl = new StringBuilder(url);
            if (requestLine != null && !requestLine.isEmpty()) {
                // 如果請求參數不為空,則在請求時添加上這些參數
                requestUrl.append("?");
                Set<String> paramKeys = requestLine.keySet();
                Iterator<String> it = paramKeys.iterator();
                String paramKey;
                String paramValue;
                while (it.hasNext()) {
                    paramKey = it.next();
                    paramValue = StringUtils.defaultIfEmpty(requestLine.get(paramKey),"");
                    requestUrl.append(paramKey).append("=").append(URLEncoder.encode(paramValue,"UTF-8"));
                    if (it.hasNext()) {
                        requestUrl.append("&");
                    }
                }
            }
            String messageId = UUID.randomUUID().toString().replaceAll("-" , "");
            InterfaceLog.request(messageId, requestUrl == null ? "無位址" : requestUrl.toString(),"GET",
                    requestLine == null ? "無參數" : requestLine.toString());
            URL objUrl = new URL(requestUrl.toString());
            httpConn = (HttpURLConnection) objUrl.openConnection();
            // 添加請求頭部
            httpConn.setRequestMethod("GET");
            int rspCode = httpConn.getResponseCode();
            inpRead = getInputStreamReader(httpConn);
            inputStreamOfHttpRsp = new BufferedReader(inpRead);
            String inputLine;
            StringBuffer httpRspStringBuffer = new StringBuffer();
            while (null != inputStreamOfHttpRsp && (inputLine = inputStreamOfHttpRsp.readLine()) != null) {
                httpRspStringBuffer.append(inputLine);
            }
            InterfaceLog.response( messageId, requestUrl.toString(), httpConn.getRequestMethod(), rspCode, ObjectUtils.toString(httpRspStringBuffer));
            Object rspResult;
            try{
                rspResult = JSON.parseObject(httpRspStringBuffer.toString());
            } catch (Exception e){
                rspResult = JSON.parseArray(httpRspStringBuffer.toString());
            }
            checkRespValid(rspResult);
            return rspResult;
        } catch (MalformedURLException e) {
            logger.error("GET-Http請求Url異常--->", e);
        } catch (ProtocolException e) {
            logger.error("協定異常--->", e);
        } catch (IOException e) {
            logger.error("GET-Http請求過程中IO異常--->", e);
        } catch (Exception e){
            logger.error("GET請求中其他異常", e);
        } finally {
            try {
                if (inputStreamOfHttpRsp != null) {
                    inputStreamOfHttpRsp.close();
                }
                if (inpRead != null) {
                    inpRead.close();
                }
                if (httpConn != null) {
                    httpConn.disconnect();
                }
            } catch (IOException e) {
                logger.error("關閉資源失敗--->", e);
            }
        }
        throw new HttpResponseOfInterfaceException("GET請求失敗");
    }
           

(以上代碼包含一些自定義内容,請自行修改)

定義完拼接請求參數的方法,我們就可以在【web】子產品中進行接口調用啦:

Map<String, String> requestParam = new HashMap<>();
requestParam.put("***", ***);
sendGetRequest(getURL(),requestParam);