假设我有一个像这样的 JAX-RS Web 服务:
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
@Path("/somePath/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class SomeObject {
@PathParam("id")
private String id;
@GET
@Path("/something")
public String something() {
DbObject dbObject = new DbObject(id);
// return something
}
@POST
@Path("/somethingElse")
public void somethingElse(Arg1 arg1, Arg2 arg2) {
DbObject dbObject = new DbObject(id);
// do something else with it
}
...
}
几乎所有方法中的第一行都是创建我的 dbObject。
有没有办法在设置id后立即执行此操作?
我可以在 id setter 中执行此操作吗?是否会调用 setId 方法而不是填充 id 变量的值?
或者我还有什么其他选择?
最佳答案
引用 @PathParam
文档:
The type of the annotated parameter, field or property must either:
- Be
PathSegment
, the value will be the final segment of the matching part of the path. SeeUriInfo
for a means of retrieving all request path segments.- Be
List<javax.ws.rs.core.PathSegment>
, the value will be a list of PathSegment corresponding to the path segment(s) that matched the named template parameter. SeeUriInfo
for a means of retrieving all request path segments.- Be a primitive type.
- Have a constructor that accepts a single
String
argument.- Have a static method named
valueOf
orfromString
that accepts a singleString
argument (see, for example,Integer.valueOf(String)
).- Have a registered implementation of
ParamConverterProvider
JAX-RS extension SPI that returns aParamConverter
instance capable of a "from string" conversion for the type.
如果您满足上述条件之一,您将能够使用:
@PathParam("id")
private DbObject dbObject;
让我们重点关注最后三种方法。首先,使用带有单个 String
的构造函数论据:
public class DbObject {
private String id;
public DbObject(String id) {
this.id = id;
}
...
}
或者您可以使用valueOf(String)
方法:
public class DbObject {
private String id;
public DbObject(String id) {
this.id = id;
}
public static DbObject valueOf(String id) {
return new DbObject(id);
}
...
}
或者定义一个 ParamConverterProvider
:
@Provider
public class DbObjectParamConverterProvider implements ParamConverterProvider {
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType,
Annotation[] annotations) {
if (rawType.getName().equals(DbObject.class.getName())) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
return rawType.cast(new DbObject(value));
}
@Override
public String toString(T value) {
return ((DbObject) value).getId();
}
};
}
return null;
}
}
关于java - 如何使用实例PathParam创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49153809/