泽西岛:获取方法的URL

nik*_*tix 5 java uri builder jersey

我想获取特定方法的URI,而无需对其进行“硬编码”。

我试过了,UriBuilder.fromMethod但是它只生成在该@Path方法的注释中指定的URI,没有考虑@Path它所在的资源类。

例如,这是课程

@Path("/v0/app")
public class AppController {

    @Path("/{app-id}")
    public String getApp(@PathParam("app-id") int appid) {
        // ...
    }

}
Run Code Online (Sandbox Code Playgroud)

我想获取getApp方法的URL ,/v0/app/100例如。

更新:

我想从其他方法获取URL getApp

Pau*_*tha 5

如果您使用,则可以使用UriBuilder.fromResource,然后添加方法路径path(Class resource, String method)

URI uri = UriBuilder
        .fromResource(AppController.class)
        .path(AppController.class, "getApp")
        .resolveTemplate("app-id", 1)
        .build();
Run Code Online (Sandbox Code Playgroud)

不知道为什么它不能与 一起使用fromMethod

这是一个测试用例

public class UriBuilderTest {

    @Path("/v0/app")
    public static class AppController {

        @Path("/{app-id}")
        public String getApp(@PathParam("app-id") int appid) {
            return null;
        }
    }

    @Test
    public void testit() {
       URI uri = UriBuilder
               .fromResource(AppController.class)
               .path(AppController.class, "getApp")
               .resolveTemplate("app-id", 1)
               .build();

        assertEquals("/v0/app/1", uri.toASCIIString());
    }
}
Run Code Online (Sandbox Code Playgroud)