java 在 jersey 中以编程方式注册一个提供者,它实现了异常映射器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31501110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:42:54  来源:igfitidea点击:

Registering a provider programmatically in jersey which implements exceptionmapper

javaweb-servicesrestjersey

提问by Gautam

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?

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

For example:

例如:

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();
    }
}

Is this the correct way to do this?

这是正确的方法吗?

回答by Paul Samsotha

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 douse it, it should be it's own separate class. There you can register the mapper.

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

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

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

但您可能正在使用 web.xml。在这种情况下,您可以使用以下内容注册提供程序<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>

Have a look at Application Deployment and Runtime Environmentsfor 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).

有关不同部署模型的更多信息,请查看应用程序部署和运行时环境。部署应用程序有几种不同的方法。您甚至可以混合搭配(web.xml 和 ResourceConfig)。

回答by ursa

While @paul-samsotha's answer is correct, still there is implementation trick. I want to share it and hope it will help someone.

虽然@paul-samsotha 的回答是正确的,但仍有实现技巧。我想分享它,希望它能帮助别人。

a) Implement your mapper:

a) 实现你的映射器:

public class MyExceptionMapper implements ExceptionMapper<Throwable>, ResponseErrorMapper {
    ...

b) make sure you declare generic type, otherwise your mapper will never be called

b) 确保您声明泛型类型,否则您的映射器将永远不会被调用

public class MyExceptionMapper implements ExceptionMapper/* no generic declaration */, ResponseErrorMapper {
    ...

and may trigger

并且可能触发

javax.ws.rs.ProcessingException: Could not find exception type for given ExceptionMapper class: class com...MyExceptionMapper.

c) Register it as resource:

c) 将其注册为资源:

ResourceConfig config = new ResourceConfig();
config.register(new MyExceptionMapper());

or

或者

config.register(MyExceptionMapper.class);

d) make sure you enforce processing errors as well:

d) 确保您也强制执行处理错误:

config.setProperties(new LinkedHashMap<String, Object>() {{
    put(org.glassfish.jersey.server.ServerProperties.PROCESSING_RESPONSE_ERRORS_ENABLED, true);
}});

回答by Archimedes Trajano

If you're using Spring and want to register the providers programmatically based on the presence of @Pathand @Providerannotation you can use the following technique

如果您正在使用 Spring 并希望根据存在@Path@Provider注释以编程方式注册提供程序,您可以使用以下技术

@Component
public class JerseyConfig extends ResourceConfig {

  @Autowired
  private ApplicationContext applicationContext;

  @PostConstruct
  public init() {

    applicationContext.getBeansWithAnnotation(Path.class).values().forEach(
      component -> register(component.getClass())
    );
    applicationContext.getBeansWithAnnotation(Provider.class).values().forEach(
      this::register
    );
  }
}