简体   繁体   English

Spring-Boot需要构造函数中的泛型类型

[英]Spring-Boot Generic type in constructor needed

I've encountered a problem in my code and I'm looking for a workaround. 我在我的代码中遇到了问题,我正在寻找一种解决方法。 This is the class: 这是课程:

import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventsourcing.EventSourcedAggregateRoot;
import org.axonframework.eventsourcing.EventSourcingRepository;
import org.axonframework.eventstore.EventStore;
import org.axonframework.repository.LockManager;
import org.axonframework.repository.PessimisticLockManager;
import org.axonframework.repository.Repository;
import org.springframework.stereotype.Component;

@Component
public class BaseCommandHandler<E extends EventSourcedAggregateRoot> {

  protected Repository<E> repository;
  protected LockManager lockManager;

  /**
   * @param eventBus eventBus.
   * @param eventStore eventStore.
   */
  public BaseCommandHandler(EventBus eventBus, EventStore eventStore) {
    this.lockManager = new PessimisticLockManager();
    EventSourcingRepository<E> newRepository =
        new EventSourcingRepository<>(E.class, eventStore, lockManager);
    newRepository.setEventBus(eventBus);
  }
}

The first problem I faced was that I cannot use E.class . 我遇到的第一个问题是我不能使用E.class Then I changed the constructor to the following: 然后我将构造函数更改为以下内容:

  public BaseCommandHandler(EventBus eventBus, EventStore eventStore, Class<E> type) {
    this.lockManager = new PessimisticLockManager();
    EventSourcingRepository<E> newRepository =
        new EventSourcingRepository<>(type, eventStore, lockManager);
    newRepository.setEventBus(eventBus);
  }
}

But when I ran the app it failed to start because of Parameter 2 of constructor in com.domain.handlers.BaseCommandHandler required a bean of type 'java.lang.Class' that could not be found. 但是当我运行应用程序时,它无法启动,因为Parameter 2 of constructor in com.domain.handlers.BaseCommandHandler required a bean of type 'java.lang.Class' that could not be found.Parameter 2 of constructor in com.domain.handlers.BaseCommandHandler required a bean of type 'java.lang.Class' that could not be found.

How can I solve this issue? 我该如何解决这个问题?

You can use GenericTypeResolver class: 您可以使用GenericTypeResolver类:

Class<E> type = (Class<E>) GenericTypeResolver.resolveTypeArgument(getClass(), BaseCommandHandler.class);
EventSourcingRepository<E> newRepository = new EventSourcingRepository<>(type, eventStore, lockManager);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM