代码之家  ›  专栏  ›  技术社区  ›  Boudhayan Dev

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

  •  0
  • Boudhayan Dev  · 技术社区  · 6 年前

    我想 autowire 一个例子 OkHttpClient 在我的控制器课上。我创造了一个 OkHttpClientFactory 类并将其标记为 Bean 在它的构造函数中。我把这个作为一个例子 Autowired 在控制器类中。然而,我遇到了以下问题-

    豆子-

    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
    

    不是吗 自动装配 OkHttpClientFactory 实例实际返回 OkHttpClient 类型那为什么是这种方法呢 newCall() 不适用吗?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Adil Khalil    6 年前

    改变这个 @Autowired private OkHttpClientFactory client; 在你的控制器里。

    @Autowired private OkHttpClient client;
    

    你想@autowire到 OKHttpClient 而不是“工厂”类。

        2
  •  2
  •   Michał Krzywański    6 年前

    您的工厂是一个配置类,因为您用 @Configuration 注释。在控制器中,不要注入配置bean,而是注入在其中配置的bean。这个bean将在spring上下文中可用,并且对 @Autowire .

    班级 OkHttpClientFactory 没有办法 newCall(Request) 如你所见。 你应该换个场地 private OkHttpClientFactory client; 在你的控制器中 private OkHttpClient client; 让spring按类型注入豆子。