1

我不知道这是否可能,但这是我的问题:我有一个使用 spring-boot 和 spring-batch 开发的批处理,我必须使用 Feign 调用另一个微服务......帮助!

这是我的班级阅读器

package it.batch.step;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import it.client.feign.EmailAccountClient;
import it.dto.feign.mail.account.AccountOutDto;
import it.dto.feign.mail.account.SearchAccountFilterDto;
import it.dto.feign.mail.account.SearchAccountResponseDto;

public class Reader implements ItemReader <String> {

    private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class);

    private int count = 0;

    @Autowired
    private EmailAccountClient emailAccountClient;

    @Override
    public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {

        LOGGER.info("read - begin ");
        SearchAccountResponseDto clientResponse = emailAccountClient.searchAccount(getFilter());
        if (count < clientResponse.getAccounts().size()) {
            return convertToJsonString(clientResponse.getAccounts().get(count++));
        } else {
            count = 0;
        }
        return null;
    }

    private static SearchAccountFilterDto getFilter() {
        SearchAccountFilterDto filter = new SearchAccountFilterDto();

        return filter;
    }

    private String convertToJsonString(AccountOutDto account) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = "";
        try {
            jsonString = mapper.writeValueAsString(account);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        LOGGER.info("Contenuto JSON: " + jsonString);
        return jsonString;
    }
}

...当我启动批处理时出现此错误:

java.lang.NullPointerException: null
    at it.batch.step.Reader.read(Reader.java:32) ~[classes/:?]

其中第 32 行是:

SearchAccountResponseDto clientResponse = emailAccountClient.searchAccount(getFilter());

EmailAccountClient 为空

4

1 回答 1

0

您的客户端为空:您的阅读器不是 @Component,因此 Spring 无法自动装配客户端。当您实例化阅读器时,您必须使用一种解决方法,例如通过构造函数传递自动装配的客户端,如下所示:

 private EmailAccountClient client;

 public reader(EmailAccountClient client){

  this.client=client;
  }

在另一个班级:

  @Autowired
  private EmailAccountClient client;

  @Bean
  public ItemReader<String> reader(){

      return new Reader(client)

  }
于 2020-04-24T09:21:52.783 回答