у меня два класса
@Component
public class EventProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(EventProcessor.class);
@Autowired
private MyProperties myProperties;
/**
* Listens to the Event hub
*
* @throws InterruptedException
* @throws ExecutionException
*/
public void startProcess() throws Exception {
EventProcessorHost host = new EventProcessorHost(
EventProcessorHost.createHostName(myProperties.getEventproperties().getHostNamePrefix(),
myProperties.getEventproperties().getEventHubName(),
myProperties.getEventproperties().getConsumerGroupName(),
myProperties.getEventproperties().getEventHubConnectionString(),
myProperties.getEventproperties().getStorageConnectionString(),
myProperties.getEventproperties().getStorageContainerName());
EventProcessorOptions options = new EventProcessorOptions();
host.registerEventProcessor(AzureEventHubReceiver.class, options).get();
}
}
а также
@Component
public class AzureEventHubReceiver implements IAzureEventHubReceiver {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureEventHubReceiver.class);
private int checkpointBatchingCount = 0;
@Autowired
private IDeployStatusService deployStatusService;
@Override
public void onOpen(PartitionContext context) throws Exception {
}
@Override
public void onClose(PartitionContext context, CloseReason reason) throws Exception {
}
@Override
public void onError(PartitionContext context, Throwable error) {
}
/*
*
*/
@Override
public void onEvents(PartitionContext context, Iterable<EventData> events)
throws InterruptedException, ExecutionException, JsonParseException, JsonMappingException, IOException {
for (EventData data : events) {
// Gson gson = new GsonBuilder().create();
ObjectMapper objectMapper = new ObjectMapper();
// EventHubModel model = null;
EventHubModel[] model = objectMapper.readValue(new String(data.getBytes(), "UTF8"), EventHubModel[].class);
if (model!=null && deployStatusService!=null) {
deployStatusService.saveOrUpdateToDb(model[0].getData().getCorrelationId(), model[0].getData().getStatus());
}
this.checkpointBatchingCount++;
if ((checkpointBatchingCount % 5) == 0) {
context.checkpoint(data).get();
}
}
}}
Класс процессора событий загружается при запуске Springboot с использованием команды CommandLineRunner.
@Component
public class EventProcessorRunner implements CommandLineRunner{
@Autowired
private EventProcessor processor;
EventProcessorRunner(final EventProcessor processor) {
this.processor = processor;
}
@Override
public void run(String... args) throws Exception {
processor.startProcess();
}
}
Интерфейс IDeployStatus показан ниже.
public interface IDeployStatusService {
void saveCorrelationId(String correlationId,Long serviceId, Long userSubscriptionId, ProvisioningState provisioningState);
void saveOrUpdateToDb(String correlationId, String status);
}
и реализация
@Service
public class DeployStatusService implements IDeployStatusService {
private static final Logger LOGGER = LoggerFactory.getLogger(DeployStatusService.class);
@Autowired
IServiceConverter serviceConverter;
@Autowired
ServiceRepo serviceRepo;
@Autowired
IDeployConverter deployConverter;
@Autowired
ISubConverter subConverter;
@Autowired
SubRepository subRepo;
@Autowired
ServiceDeployRepository serviceDeployRepository;
@Override
public void saveCorrelationId(String correlationId, Long serviceId, Long userSubscriptionId,
ProvisioningState provisioningState) {
}
Однако IDeployStatusService не инициализируется и всегда возвращает значение null, даже когда событие запускается из API, и элемент управления достигает здесь. Любая идея относительно того, что можно сделать? Я пытался сделать инъекцию конструктора здесь, в deployStatusService, но безрезультатно.
конечно. опубликую это здесь. Извините, я явно пропустил это.
host.registerEventProcessor создает new DeployStatusService? Если это так, то этот экземпляр не является компонентом Spring. Переход к внедрению конструктора вместо внедрения поля поможет выявить подобные проблемы.
host.registerEventProcessor(AzureEventHubReceiver.class, options).get(); регистрирует этот и этот класс AzureEventHubReceiver, в свою очередь, имеет автосвязывание IDeployStatusService. Я попробовал внедрение конструктора, предоставив общедоступный AzureEventHubReceiver (IDeployStatusService deployStatusService) {this.deployStatusService = deployStatusService;. Однако я все еще получаю его как null
используя внедрение конструктора, я получаю следующую ошибку java.lang.InstantiationException: com.xxxx.service.impl.AzureEventHubReceiver Вызвано: java.lang.NoSuchMethodException: com.xxxx.service.impl.AzureEventHubReceiver.<init>()
Взгляните на где следует применять @Autowired?.
К сожалению, этот NIkolay не помогает в этом случае.
@chrylis тоже сделал это, но все же это null. Может быть, это как-то связано с новым в EventProcessor, что Spring не может управлять bean-компонентом в AzureEventHubReceiver
@Codeip Это исключение говорит вам, что кто-то (кто бы ни отвечал за registerEventProcessor) пытается создать экземпляр класса, который вы передаете, с помощью конструктора по умолчанию. Посмотрите документацию и посмотрите, можете ли вы передать экземпляр вместо класса.




У вас есть действительный
Beanдля реализацииIDeployStatusService?