[英]Dependency injection with @Inject and Interface in Quarkus
I'm trying to resolve dependency injection with Repository Pattern using Quarkus 1.6.1.Final and OpenJDK 11. I want to achieve Inject with Interface and give them some argument(like @Named
or @Qualifier
) for specify the concrete class, but currently I've got UnsatisfiedResolutionException
and not sure how to fix it.我正在尝试使用 Quarkus 1.6.1.Final 和 OpenJDK 11 使用 Repository Pattern 解决依赖注入。我想实现 Inject with Interface 并给他们一些参数(如
@Named
或@Qualifier
)以指定具体的 class,但目前我有UnsatisfiedResolutionException
并且不知道如何解决它。
Here is the my portion of code.这是我的代码部分。
UseCase class:用例 class:
@ApplicationScoped
public class ProductStockCheckUseCase {
@Inject
@Named("dummy")
ProductStockRepository repo;
public int checkProductStock() {
ProductStock stock = repo.findBy("");
return stock.getCount();
}
}
Repository Interface:存储库接口:
public interface ProductStockRepository {
public ProductStock findBy(String productId);
}
Repository Implementation:存储库实现:
@Named("dummy")
public class ProductStockDummyRepository implements ProductStockRepository {
public ProductStock findBy(final String productId) {
final ProductStock productStock = new ProductStock();
return productStock;
}
}
And here is a portion of my build.gradle's dependencies:这是我的 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'
}
When I run this (eg ./gradlew assemble
or ./gradlew quarkusDev
), I've got the following errors:当我运行它时(例如
./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]
Do you have any ideas how to fix this?你有任何想法如何解决这个问题吗? or is it wrong idea to implement this kind of interface injection and specify the concrete class with argument/annotation?
还是实现这种接口注入并使用参数/注释指定具体的 class 是错误的想法?
I've read and tried the following articles:我已阅读并尝试过以下文章:
Some official docs:一些官方文档:
The other blogs and SOs:其他博客和 SO:
My guess is that you need to add a scope annotation to your ProductStockDummyRepository
.我的猜测是您需要在
ProductStockDummyRepository
添加一个 scope 注释。 Probably either @Singleton
or @ApplicationScoped
.可能是
@Singleton
或@ApplicationScoped
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.