在实现异常映射器的球衣中以编程方式注册提供程序

Registering a provider programmatically in jersey which implements exceptionmapper(在实现异常映射器的球衣中以编程方式注册提供程序)

本文介绍了在实现异常映射器的球衣中以编程方式注册提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在实现 jersey API 提供的 Exceptionmapper 的 jersey 中以编程方式注册我的提供程序?我不想使用@Provider 注解,想使用 ResourceConfig 注册提供者,我该怎么做?

How do I register my provider programmatically in jersey which implements the Exceptionmapper provided by jersey API? I don't want to use @Provider annotation and want to register the provider using ResourceConfig, how can I do that?

例如:

public class MyProvider implements ExceptionMapper<WebApplicationException> extends ResourceConfig {

     public MyProvider() {
        final Resource.Builder resourceBuilder = Resource.builder();
        resourceBuilder.path("helloworld");

        final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
        methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE)
                .handledBy(new Inflector<ContainerRequestContext, String>() {

            @Override
            public String apply(ContainerRequestContext containerRequestContext) {
                return "Hello World!";
            }
        });

        final Resource resource = resourceBuilder.build();
        registerResources(resource);
    }

    @Override
    public Response toResponse(WebApplicationException ex) {
        String trace = Exceptions.getStackTraceAsString(ex);
        return Response.status(500).entity(trace).type("text/plain").build();
    }
}

这是正确的做法吗?

推荐答案

我猜你没有 ResourceConfig,因为你似乎不确定如何使用它.一方面,它不是必需的.如果你确实使用它,它应该是它自己独立的类.在那里你可以注册映射器.

I'm guessing you don't have a ResourceConfig, since you seem to not be sure how to use it. For one, it is not required. If you do use it, it should be it's own separate class. There you can register the mapper.

public class AppConfig extends ResourceConfig {
    public AppConfig() {
        register(new MyProvider());
    }
}

但您可能正在使用 web.xml.在这种情况下,您可以使用以下 <init-param>

But you are probably using a web.xml. In which case, you can register the provider, with the following <init-param>

<servlet>
    <servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            org.foo.providers.MyProvider
        </param-value>
    </init-param>
</servlet>

看看 Jersey 2 中的 ResourceConfig 类到底是什么? 了解有关不同部署模型的更多信息.有几种不同的方式来部署应用程序.您甚至可以混合搭配(web.xml 和 ResourceConfig).

Have a look at What exactly is the ResourceConfig class in Jersey 2? for more information on different deployment models. There are a few different ways to deploy applications. You can even mix and match (web.xml and ResourceConfig).

这篇关于在实现异常映射器的球衣中以编程方式注册提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在实现异常映射器的球衣中以编程方式注册提供程序

基础教程推荐