当前位置: 首页 > 知识库问答 >
问题:

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

钱弘壮
2023-03-14

我在代码中遇到了一个问题,我正在寻找解决方法。这是一节课:

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);
  }
}

我面临的第一个问题是我不能使用E.class。然后,我将构造函数更改为以下内容:

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

但当我运行应用程序时,由于com中构造函数的参数2,它无法启动。领域处理程序。BaseCommandHandler需要“java”类型的bean。“lang.Class”无法找到

我如何解决这个问题?

共有1个答案

丁英韶
2023-03-14

您可以使用GenericTypeResolver类:

Class<E> type = (Class<E>) GenericTypeResolver.resolveTypeArgument(getClass(), BaseCommandHandler.class);
EventSourcingRepository<E> newRepository = new EventSourcingRepository<>(type, eventStore, lockManager);
 类似资料:
  • 问题内容: 我有两个类,和,扩展了前一个类。 具有以下构造函数: 我将注意到所有实例变量都已设置为private。 同时,具有以下构造函数: 但是,这为我的构造函数引发了“找不到符号”错误。 我尝试使用,但是我的超类的私有范围阻止了这种情况。 我发现向我的构造函数中添加字段并允许我调用超级构造函数,但是我想知道是否存在一种无需在子类构造函数中传递其所有参数的情况下调用超级构造函数的方法? 问题答案

  • 请帮我从这段代码中查找错误。我还是新手,我不知道这是否正确。我确实有一个错误。这就是错误:类Person中的构造函数Person不能应用于给定类型;super();^requiredent:String,String,String找到:没有参数原因:实际和正式参数列表长度不同这是我的代码: 编辑:如果我对Person和Address类都这样做。我只能有三个ARG构造函数。如何调用one-arg构造

  • 问题内容: 除了* 使用如下所示的反射检查 之外 ,是否有任何方法 要求 类具有默认(无参数)构造函数?(以下方法可以工作,但是很hacky,反射速度很慢) * 问题答案: 您可以为此构建一个注释处理器。注释处理器是在编译时运行的编译器插件。它们的错误显示为编译器错误,甚至可能停止构建。 这是一个示例代码(尽管我没有运行它): 如果引入注释(例如RequiresDefaultAnnotation)

  • 在此处输入图像描述 在此处输入图像描述 我仍然不知道该怎么办(我在UserRepository上尝试了Repository注释-错误是一样的)。错误消息:`启动ApplicationContext时出错。要显示条件报告,请在启用“调试”的情况下重新运行应用程序。2022-03-14 09:04:54.626错误7236---[main]o.s.b.d.LoggingFailureAnalysisR

  • 我问这个问题是因为在Python和Java中,如果父类构造函数需要0参数,则不需要调用super()。 Javascript 蟒蛇 Java

  • 想改进这个问题吗 通过编辑此帖子,添加详细信息并澄清问题。 我问这个问题是因为在Python和Java中,如果父类构造函数需要0参数,则不需要调用super()。 Javascript 蟒蛇 Java语言