我想在我的 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/