簡體   English   中英

如何在Spring Boot中自動連接OkHttpClient bean?

[英]How to Autowire a OkHttpClient bean in Spring Boot?

我想在Controller類中autowire OkHttpClient的實例。 我創建了一個OkHttpClientFactory類,並在其構造函數中將其標記為Bean 我將其作為Autowired在Controller類中。 但是,我遇到了以下問題-

豆角,扁豆 -

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import okhttp3.OkHttpClient;

@Configuration

public class OkHttpClientFactory {
    @Bean
    public OkHttpClient OkHttpClientFactory() {
        return new OkHttpClient();
    }


}

控制器-

import java.io.IOException;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sap.lmc.beans.OkHttpClientFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@RestController
@RequestMapping("/recast")
public class Test {

    @Autowired
    private OkHttpClientFactory client;

    private String url = "https://example.com/";

    @GetMapping(path="/fetchResponse", produces="application/json")
    public String getRecastReponse() {

        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            JSONObject json = new JSONObject();
            json.put("conversation",response.body().string());
            return json.toString();
        } catch (IOException e) {
            return e.getMessage().toString();
        }   
    }

}

出現以下錯誤結果-

java.lang.Error: Unresolved compilation problem: 
    The method newCall(Request) is undefined for the type OkHttpClientFactory

Autowired OkHttpClientFactory實例實際上不是返回OkHttpClient類型的對象OkHttpClient 那么為什么newCall()方法不適用呢?

更改此@Autowired private OkHttpClientFactory client; 在您的控制器中。

@Autowired private OkHttpClient client;

您想要@autowire到OKHttpClient而不是'Factory'類。

您的工廠是配置類,因為您使用@Configuration注釋對其進行了注釋。 在您的控制器中,不要注入配置Bean,而是注入其中配置的Bean。 該bean將在spring上下文中可用,並且對@Autowire有效。

OkHttpClientFactory沒有法newCall(Request) ,你可以很明顯的看出。 您應該更改字段private OkHttpClientFactory client; 在您的控制器中,以private OkHttpClient client; 然后讓spring按類型注入bean。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM