2017-07-11 32 views
1

examples that I've found讨论了如何在unmarshaller对象上设置验证处理程序。如何在Jersey中使用Moxy注册ValidationEventHandler?

但是,使用Jersey,MOXy/JAXB为我初始化,我不知道如何访问unmarshaller。

目前,我像这样引导Jersey,jersey-media-moxy在类路径上。

@ApplicationPath("rest") 
public class ApplicationConfig extends ResourceConfig { 
    Logger logger = LoggerFactory.getLogger(ApplicationConfig.class); 

    public ApplicationConfig() { 
     // Scan classes in this package and subpackages 
     logger.info("Registering REST Application"); 
     packages("rest"); 
     register(new AbstractBinder() { 
      @Override 
      protected void configure() { 
       // used to automatically inject a Connection instance and close it 
       bindFactory(ConnectionFactory.class).to(Connection.class) 
         .proxy(true).proxyForSameScope(false).in(RequestScoped.class); 
      } 
     }); 


    } 
} 

用这种方法,我怎么能注册的解组一个ValidationEventHandler

回答

1

我不知道这是否是正确的方式来做到这一点(我从来没有这样做),但做一些挖掘the source code,你可以扩大ConfigurableMoxyJsonProvider并覆盖preReadFrom

我看不出有其他办法可以做到。前面提到的课程延伸MoxyJsonProvider。你可以在readFrom中看到,当Unmarahsaller被创建时,你可以用它做很多事情。你所能做的就是从外面设置属性。但没有什么能让你访问实际的Unmarshaller。所以也许只有这样才能访问它来扩展提供者。

您可能还需要禁用默认的MOXy提供程序。例如

@Consumes("application/json") 
@Produces("application/json") 
public class ValidatingMoxyProvider extends ConfigurableMoxyJsonProvider { 
    private final ValidationEventHandler handler = event -> { 
     System.out.println(event.getLinkedException()); 
     System.out.println(event.getMessage()); 
     return false; 
    }; 

    @Override 
    protected void preReadFrom(final Class<Object> type, 
           final Type genericType, 
           final Annotation[] annotations, 
           final MediaType mediaType, 
           final MultivaluedMap<String, String> httpHeaders, 
           final Unmarshaller unmarshaller) throws JAXBException { 
     super.preReadFrom(type, genericType, annotations, 
          mediaType, httpHeaders, unmarshaller); 
     unmarshaller.setEventHandler(handler); 
    } 
} 

public ApplicationConfig() { 
    register(ValidatingMoxyProvider.class); 
    property(ServerProperties.MOXY_JSON_FEATURE_DISABLE, true); 
} 

如果你担心什么,你可能会被禁用,只是看在source for the MoxyJsonFeature。除非你使用entity filtering feature

你不会错过任何东西
相关问题