【问题标题】:Dependency injection with @Inject and Interface in Quarkus在 Quarkus 中使用 @Inject 和接口进行依赖注入
【发布时间】:2020-12-04 08:14:58
【问题描述】:

我正在尝试使用 Quarkus 1.6.1.Final 和 OpenJDK 11 通过存储库模式解决依赖注入问题。 我想实现 Inject with Interface 并给他们一些参数(如 @Named 或 @Qualifier )以指定具体类,但目前我有 UnsatisfiedResolutionException 并且不知道如何修复它。

这是我的部分代码。

用例类:

@ApplicationScoped
public class ProductStockCheckUseCase {
    @Inject
    @Named("dummy")
    ProductStockRepository repo;

    public int checkProductStock() {
        ProductStock stock = repo.findBy("");
        return stock.getCount();
    }
}

存储库接口:

public interface ProductStockRepository {
    public ProductStock findBy(String productId);
}

存储库实现:

@Named("dummy")
public class ProductStockDummyRepository implements ProductStockRepository {

    public ProductStock findBy(final String productId) {
        final ProductStock productStock = new ProductStock();
        return productStock;
    }
}

这是我的 build.gradle 依赖项的一部分:

dependencies {
    implementation 'io.quarkus:quarkus-resteasy'
    implementation 'io.quarkus:quarkus-arc'
    implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")

    testImplementation 'io.quarkus:quarkus-junit5'
    testImplementation 'io.rest-assured:rest-assured'
}

当我运行此程序(例如 ./gradlew assemble 或 ./gradlew quarkusDev )时,出现以下错误:

Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type ProductStockRepository and qualifiers [@Named(value = "dummy")]
        - java member: ProductStockCheckUseCase#repo
        - declared on CLASS bean [types=[ProductStockCheckUseCase, java.lang.Object], qualifiers=[@Default, @Any], target=ProductStockCheckUseCase]

您对如何解决此问题有任何想法吗?还是实现这种接口注入并使用参数/注释指定具体类是错误的想法?

我已阅读并尝试过以下文章:

一些官方文档:

其他博客和 SO:

【问题讨论】:

    标签: java spring cdi quarkus


    【解决方案1】:

    我的猜测是您需要在ProductStockDummyRepository 中添加范围注释。可能是@Singleton 或@ApplicationScoped。

    【讨论】:

    • 哇......是的,它有效。我错过了那个注释,花了两个多小时。谢谢你的回答,我真的很感激。
    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多