【问题标题】:Autowire bean in spring boot return null? [duplicate]Spring Boot中的Autowire bean返回null? [复制]
【发布时间】:2021-10-28 08:48:38
【问题描述】:

我使用 OkHttp 创建了对另一台服务器的请求调用,我使用 Autowired 向它注入 bean 似乎不起作用。

这是我的配置 bean

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

这是我的类调用请求

@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>>() {
        });
    }

}

当我检查okHttpClient时,它在方法内返回null?这是为什么?我要修吗?

【问题讨论】:

  • 你没有显示你在哪里使用 GraphQLImpl.
  • GraphQLImpl graphQLImpl = new GraphQLImpl();然后使用里面的方法。

标签: java spring-boot okhttp


【解决方案1】:

在您的HttpConfiguration 类中,您使用的是@Configurable,这是用于创建带有new 关键字为@Autowired 的对象。基本上@Configurable 使用 AspectJ 编译时编织来注入您的对象。这需要代码配置。但是,为了简单起见,我建议您对 HttpConfiguration 类使用 @Configuration 注释。

您将通过下面提到的先前发布的问题获得更多信息。

Why is my Spring @Autowired field null?

希望这能解决您的问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2019-03-14
    • 2020-02-25
    相关资源
    最近更新 更多