1

I have created a request call to another server using OkHttp and I using Autowired to inject a bean to it seem not working.

This is my configuration bean

@Configurable
public class HttpConfiguration {
    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient();
    }
}

This is my class to call the request

@Component
@Slf4j
public class GraphQLImpl  {

    @Autowired
    public OkHttpClient okHttpClient;

    public List<Product> getProducts( int countryId, String URL, String token, List<String> articleIds) {
        DefaultGraphQLClient graphQLClient = new DefaultGraphQLClient(URL);
        GraphQLResponse response = graphQLClient.executeQuery(QueryUtils.getProductsQuery(articleIds, PartitionUtil.getReadPartition(token), countryId), new HashMap<>(), "", (url, headers, body) -> {
                Request request = new Request.Builder()
                    .header("Authorization", "Bearer " + token)
                    .url(url)
                    .post(RequestBody.create(okhttp3.MediaType.parse("text/x-markdown"), body))
                    .build();
                try {
                    Response responseOkHttp = okHttpClient.newCall(request).execute();
                    return new HttpResponse(responseOkHttp.code(), responseOkHttp.body().string());
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
                return new HttpResponse(404, "Can't find product");
            }
        );
        return response.extractValueAsObject("data.products[*]", new TypeRef<List<Product>>() {
        });
    }

}

When I check okHttpClient, It returns null inside the method? Why is that? I do I fix it?

Hola
  • 115
  • 6

1 Answers1

2

In your HttpConfiguration class, you are using @Configurable and that is for creating objects with new keyword to be @Autowired. Basically @Configurable with AspectJ compile-time weaving to inject your objects. This requires code configuration. However, for easy approach I suggest you to use @Configuration annotation for HttpConfiguration class.

You will get further information via the below mentioned previously posted question.

Why is my Spring @Autowired field null?

Hope this solves your problem!

Sankalpa Wijewickrama
  • 985
  • 3
  • 19
  • 30