![](/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.