如何在Spring Boot中自动连接OkHttpClient bean?

时间:2019-04-22 08:23:04

标签: java spring spring-boot dependency-injection autowired

我想在Controller类中autowire的一个实例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();
    }


}

控制器-

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()不适用于它?

2 个答案:

答案 0 :(得分:3)

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

@Autowired private OkHttpClient client;

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

答案 1 :(得分:2)

您的工厂是配置类,因为您使用@Configuration注释对其进行了注释。在您的控制器中,不要注入配置Bean,而是注入其中配置的Bean。该bean将在春季上下文中可用,并且对@Autowire有效。

您显然可以看到,类OkHttpClientFactory没有方法newCall(Request)。 您应该将控制器中的字段private OkHttpClientFactory client;更改为private OkHttpClient client;,并让spring按类型注入bean。