Quarkus中如何获取其他资源的完整URL?避免@Path变更失效
在Quarkus中安全获取资源完整URL的方案
1. 基于请求上下文构建完整URL(适用于资源方法内)
当在资源方法中需要生成其他资源的完整URL时,可结合UriInfo和UriBuilder实现——既避免硬编码路径,又能获取包含协议、主机、端口的完整地址:
import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; import java.net.URI; @Path("myresource") public class MyResource { @GET @Path("current") public URI getOtherResourceUrl(@Context UriInfo uriInfo) { // 解析目标资源的相对路径 UriBuilder resourcePathBuilder = UriBuilder.fromResource(OtherResource.class); // 结合当前请求的基础URI(协议+主机+端口+根路径)生成完整URL URI fullUri = uriInfo.getBaseUriBuilder() .path(resourcePathBuilder.build()) .build(); return fullUri; } @GET @Path("method-specific") public URI getMethodUrl(@Context UriInfo uriInfo) { // 直接生成指定方法的完整路径,自动拼接资源类和方法的@Path UriBuilder methodPathBuilder = UriBuilder.fromMethod(MyResource.class, "targetMethod"); URI fullMethodUri = uriInfo.getBaseUriBuilder() .path(methodPathBuilder.build()) .build(); return fullMethodUri; } @GET @Path("targetMethod") public String targetMethod() { return "Target method response"; } } @Path("otherresource") class OtherResource { // ... }
说明:
uriInfo.getBaseUri()会返回当前应用的基础地址(如https://localhost:8080/myapp/)UriBuilder.fromResource()/fromMethod()会自动解析类和方法上的@Path注解生成相对路径,无需硬编码
2. 无请求上下文时获取完整URL(如定时任务、后台逻辑)
如果没有请求上下文(比如定时任务),可以通过Quarkus的配置属性获取应用的基础地址,再结合UriBuilder生成完整URL:
import jakarta.enterprise.context.ApplicationScoped; import jakarta.ws.rs.Path; import org.eclipse.microprofile.config.inject.ConfigProperty; import jakarta.ws.rs.core.UriBuilder; import java.net.URI; @ApplicationScoped public class BackgroundService { @ConfigProperty(name = "quarkus.http.host", defaultValue = "localhost") String host; @ConfigProperty(name = "quarkus.http.port", defaultValue = "8080") int port; @ConfigProperty(name = "quarkus.http.root-path", defaultValue = "/") String rootPath; public URI getResourceUrl() { // 构建基础URI UriBuilder baseUriBuilder = UriBuilder.fromPath(rootPath) .scheme("http") // 根据实际环境切换http/https .host(host) .port(port); // 拼接目标资源路径 URI fullUri = baseUriBuilder .path(UriBuilder.fromResource(MyResource.class).build()) .build(); return fullUri; } }
注意:生产环境中建议通过配置管理scheme(http/https),避免硬编码。
3. 解决UriBuilder.fromMethod()路径拼接问题
如果调用UriBuilder.fromMethod(MyResource.class, "someMethod")只返回方法路径,通常是因为:
- 目标方法未添加
@Path注解:此时方法会继承类的@Path,调用fromMethod会返回类路径(而非仅方法名) - 方法的
@Path配置错误:确保类和方法的@Path注解配置正确,fromMethod会自动拼接两者的路径
示例:
@Path("myresource") public class MyResource { @GET @Path("someMethod") // 必须添加@Path注解,否则fromMethod会使用类路径 public String someMethod() { return ""; } } // 调用后返回/myresource/someMethod UriBuilder.fromMethod(MyResource.class, "someMethod").build();
内容的提问来源于stack exchange,提问作者Joost den Boer
相关产品推荐
相关产品推荐

