Quarkus中Panache REST Data仓库模式下自定义端点的仓库注入问题
解决Quarkus Panache REST Data自定义端点调用仓库方法的问题
方案1:使用CDI Current Instance获取仓库实例
在接口的default方法中,通过CDI.current()获取仓库的CDI实例,直接调用自定义方法:
import jakarta.enterprise.inject.spi.CDI; import io.quarkus.rest.data.panache.PanacheRepositoryResource; import io.quarkus.rest.data.panache.ResourceProperties; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import io.smallrye.mutiny.Uni; import java.util.List; @ResourceProperties public interface EntityResource extends PanacheRepositoryResource<EntityRepository, Entity, Long> { @GET @Path("/customMethod") default Uni<List<Entity>> repositoryMethod() { // 通过CDI获取仓库实例 EntityRepository repository = CDI.current().select(EntityRepository.class).get(); return repository.customMethod(); } }
方案2:将Resource改为抽象类(推荐)
接口的default方法无法使用@Inject注解,改用抽象类实现PanacheRepositoryResource,直接注入仓库实例:
import io.quarkus.rest.data.panache.PanacheRepositoryResource; import io.quarkus.rest.data.panache.ResourceProperties; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import io.smallrye.mutiny.Uni; import java.util.List; @ResourceProperties public abstract class EntityResource implements PanacheRepositoryResource<EntityRepository, Entity, Long> { @Inject EntityRepository entityRepository; @GET @Path("/customMethod") public Uni<List<Entity>> repositoryMethod() { return entityRepository.customMethod(); } }
关键注意事项
必须确保你的EntityRepository接口标注了@ApplicationScoped,并继承自PanacheRepository<Entity>:
import io.quarkus.hibernate.reactive.panache.PanacheRepository; import jakarta.enterprise.context.ApplicationScoped; import io.smallrye.mutiny.Uni; import java.util.List; @ApplicationScoped public interface EntityRepository extends PanacheRepository<Entity> { Uni<List<Entity>> customMethod(); }
内容的提问来源于stack exchange,提问作者zambotn
相关产品推荐
相关产品推荐

