我想创建一个球衣提供商( MessageBodyWriter )该更新DTO的对象属性,并继续链泽西JSON的默认提供一个返回JSON对象。 问题是,貌似不叫默认的提供者,所以我休息服务的输出,只要我注册新提供变空。
@Provider
public class TestProvider implements MessageBodyWriter<MyDTO>
{
@Override
public long getSize(
MyDTO arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4)
{
return 0;
}
@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] arg2, MediaType arg3)
{
return type == MyDTO.class;
}
@Override
public void writeTo(
MyDTO dto,
Class<?> paramClass,
Type paramType, Annotation[] paramArrayOfAnnotation,
MediaType mt,
MultivaluedMap<String, Object> paramMultivaluedMap,
OutputStream entityStream) //NOPMD
throws IOException, WebApplicationException
{
dto.setDescription("text Description");
// CONTINUE THE DEFAULT SERIALIZATION PROCESS
}
}
该MessageBodyWriter
不应该需要执行操作的实体的逻辑。 它的责任是根本编组/序列化。
你所寻找的,而不是为WriterIntercptor
,其目的是做什么你想被序列化之前做的,操作的实体。
这一切都说明在新泽西州督为Inteceptors这里 。
下面是一个例子
@Provider
public class MyDTOWriterInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
Object entity = context.getEntity();
if (entity instanceof MyDTO) {
((MyDTO)entity).setDescription("Some Description");
}
context.proceed();
}
}
您可以添加注释,以便只有某些资源的方法/类使用这个拦截器,如
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;
@NameBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AddDescription {
}
...
@AddDescription
@Provider
public class MyDTOWriterInterceptor implements WriterInterceptor {
...
@Path("dto")
public class MyDTOResource {
@GET
@AddDescription
@Produces(MediaType.APPLICATION_JSON)
public Response getDto() {
return Response.ok(new MyDTO()).build();
}
}
如果由于某种原因,你不能改变类(也许这就是为什么你需要在这里设置的说明,谁的都知道),那么你可以使用动态绑定 ,在这里你不需要使用注释。 你可以简单的做一些反思,检查方法或类。 该链接有一个例子。