examples that I've found讨论在 unmarshaller
对象上设置验证处理程序。
但是,使用 Jersey,MOXy/JAXB 已为我初始化,但我不知道如何访问解码器。
目前,我像这样引导 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
?
最佳答案
我不知道这是否是正确的方法(我从未这样做过),但在 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,否则您并没有真正错过任何东西。
关于java - 如何在 Jersey 中向 Moxy 注册 ValidationEventHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45034530/