java - 如何在 Spring Boot 中 Autowiring OkHttpClient bean?

标签 java spring spring-boot dependency-injection autowired

我想在我的 Controller 类中 Autowiring OkHttpClient 实例。我创建了一个 OkHttpClientFactory 类,并在其构造函数中将其标记为 Bean。我将其作为 Autowired 包含在 Controller 类中。但是,我遇到了以下问题 -

bean -

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();
    }


}

Controller -

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 类型的对象。那为什么 newCall() 方法不适用呢?

最佳答案

在您的 Controller 中更改此 @Autowired 私有(private) OkHttpClientFactory 客户端;

@Autowired private OkHttpClient client;

您想@autowire 到 OKHttpClient 而不是“Factory”类。

关于java - 如何在 Spring Boot 中 Autowiring OkHttpClient bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791346/

相关文章:

java - 检查文件中输入的字符串是否包含允许的单词

java - Solr - 索引的内存要求

java - 如何正确地将TextureRegion映射到Pixmap?

java - Spring MVC - 什么是 url 路径信息?

java - Android:创建可循环的铃声

java - 将 Hibernate 与 Spring 一起使用时,我可以摆脱 persistence.xml 吗?

java - 多个 ThreadPoolTask​​Executers Spring Java Config

java - 防止 Spring Boot 在启动时调用 EC2MetadataUtils.getItems

testing - SpringBootTest中如何覆盖应用Bean

java - Spring 启动 MailConnectException : Couldn't connect to host, 端口 : localhost, 25;超时-1;