![](/img/trans.png)
[英]How to autowire a bean in other class in a Spring Boot application?
[英]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.