Quarkus中GET接口@Path参数始终为null问题求助
问题原因与解决方法
- 核心问题:JAX-RS规范要求路径参数必须通过
@PathParam注解明确绑定到方法参数,否则容器无法自动将路径中的{key}映射到方法的key参数,导致参数始终为null。 - 额外隐患:IncrementService中的
get方法当前是包私有访问权限,若IncrementResource与IncrementService不在同一包下,会出现访问权限错误,需调整为public。
修改后的IncrementResource类
@Path("/increments") public class IncrementResource { @Inject IncrementService service; @POST public Increment create(Increment increment) { service.set(increment.key, increment.value); return increment; } @GET @Path("/{key}") public Increment get(@PathParam("key") String key) { // 添加@PathParam绑定路径参数 System.out.println(key); return new Increment(key, service.get(key)); } }
修改后的IncrementService类(关键部分)
@ApplicationScoped public class IncrementService { // 其他代码保持不变 public long get(String key) { // 将访问修饰符改为public System.out.println("getting " + key); Long value = countCommands.get(key); System.out.println("getting " + value); if (value == null) { return 0L; } return value; } // 其他代码保持不变 }
内容的提问来源于stack exchange,提问作者user19906023
相关产品推荐
相关产品推荐

