2.7.10. 创建 JAXB Decorators

RESTEasy 的 JAXB 提供程序具有一种可插拔的方式来解码不可变和 Unmarshaller 实例。您可以创建一个注解来触发某一实例或 Unmarshaller 实例,这可用于解码方法。

使用 RESTEasy 创建 JAXB Decorator
  1. 创建 Processor 类。

    1. 创建一个实现 DecoratorProcessor<Target, Annotation> 的类。目标是 JAXB#184er 或 Unmarshaller 类。该注释在第 2 步中创建。
    2. 给类标上 @DecorateTypes,再 声明解码器应解码的 MIME 类型。
    3. 在解码函数中设置属性或值。

      示例: Processor Class

      import org.jboss.resteasy.core.interception.DecoratorProcessor;
      import org.jboss.resteasy.annotations.DecorateTypes;
      import javax.xml.bind.Marshaller;
      import javax.xml.bind.PropertyException;
      import javax.ws.rs.core.MediaType;
      import javax.ws.rs.Produces;
      import java.lang.annotation.Annotation;
      
      @DecorateTypes({"text/*+xml", "application/*+xml"})
      public class PrettyProcessor implements DecoratorProcessor<Marshaller, Pretty> {
          public Marshaller decorate(Marshaller target, Pretty annotation,
            Class type, Annotation[] annotations, MediaType mediaType) {
          target.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
          }
      }

  2. 创建注解。

    1. 创建一个标有 @Decorator 注释的自定义接口。
    2. 声明 @Decorator 注释的处理器和目标。处理器在第 1 步中创建。目标是 JAXB#184 erUnmarshaller 类。

      示例:带有 @Decorator 注解的自定义接口

      import org.jboss.resteasy.annotations.Decorator;
      
      @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
      @Retention(RetentionPolicy.RUNTIME)
      @Decorator(processor = PrettyProcessor.class, target = Marshaller.class)
      public @interface Pretty {}

  3. 将第 2 步中创建的注释添加到一个函数,以便在处理时对输入或输出进行解码。

您现在已创建了 JAXB decorator,可在 Jakarta RESTful Web 服务 Web 服务中应用。