@Path("/users/{username}")
public class UserResource{
@GET
@Produces("text/xml")
public String getUser(@PathParam("username") String username){
...
}
}
我们还可以对模板参数的格式做约束,例如我们只允许大小写字符以及数字,则可以使用下面的正则表达式来限制模板参数:
@Path("/item")
public class ItemResource {
@Path("content")
public Class<ItemContentSingletonResource> getItemContentResource() {
return ItemContentSingletonResource.class;
}
}
@Singleton
public class ItemContentSingletonResource {
// this class is managed in the singleton life cycle
}
@Path("resource")
@Singleton
public static class MySingletonResource {
@QueryParam("query")
String param; // WRONG: initialization of application will fail as you cannot
// inject request specific parameters into a singleton resource.
@Path("resource")
@Singleton
public static class MySingletonResource {
@Context
Request request; // this is ok: the proxy of Request will be injected into this singleton
public MySingletonResource(@Context SecurityContext securityContext) {
// this is ok too: the proxy of SecurityContext will be injected
}
Class fields: 注入类的域中
构造函数:注入的值将用于调用构造函数
Resource Method:资源的各方法中注入
sub resource locator:不带方法注解的@Path
setter方法:只能使用@Context注解
下面是一个综合的例子:
@Path("resource")
public static class SummaryOfInjectionsResource {
@QueryParam("query")
String param; // injection into a class field
@GET
public String get(@QueryParam("query") String methodQueryParam) {
// injection into a resource method parameter
return "query param: " + param;
}
@Path("sub-resource-locator")
public Class<SubResource> subResourceLocator(@QueryParam("query") String subResourceQueryParam) {
// injection into a sub resource locator parameter
return SubResource.class;
}
public SummaryOfInjectionsResource(@QueryParam("query") String constructorQueryParam) {
// injection into a constructor parameter
}
@Context
public void setRequest(Request request) {
// injection into a setter method
System.out.println(request != null);
}
}
public static class SubResource {
@GET
public String get() {
return "sub resource";
}
}