Jersey;:通过SpringServlet注册注入的ExceptionMapper实例

J. *_*ght 6 spring jersey

泽西岛:1.12春季:3.11 JDK:1.6.0_35 Tomcat:6..0.33

我正在尝试为在SpringServlet上下文中由Spring IoC容器实例化的Jersey servlet注册ExceptionMapper实例,并且在Jersey servlet期间遇到"组件类X的范围必须是单例"异常初始化.我现在无法发布实际的代码,因此我将提供实现的基本知识,看看是否有人明显跳出某人,或者我是否可以指出我的某些文档错过.

ExceptionMapper实例基本上如下:

// ... package definitions omitted ...

@Provider
@Singleton
public class MyExceptionMapper
    implements ExceptionMapper<MyException>
{
    // ... injected attributes omitted ...

    @Override
    public Response toResponse(MyException exception)
    {
        // ... specific handling logic omitted ...

       return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();
    }
}
Run Code Online (Sandbox Code Playgroud)

applicationContext.xml中的bean定义如下,默认为singleton范围(添加显式范围说明符似乎不会改变行为):

<bean id="myExceptionMapper" class="my.package.MyExceptionMapper" />
Run Code Online (Sandbox Code Playgroud)

web.xml中的Spring上下文加载器侦听器和SpringServlet配置本质上是样板文件,当从ApplicationContext.xml中注释掉MyExceptionMapper的bean定义时,servlet将使用其他注入属性加载,初始化和正常运行.但是当applicationContext.xml中存在bean定义时,我得到了以下效果的日志消息:

SpringProviderFactory - Registering Spring bean, myExpectionMapper, of type my.package.MyExceptionMapper as a provider class
SpringProviderFactory - Registering Spring bean, myServiceController, of type my.package.MyServiceController as a root resource class
... other root resource classes loading ...
SpringServlet - Exception occurred when initialization
java.lang.RuntimeException: The scope of the component class my.package.MyExceptionMapper must be a singleton
  at som.sun.jersey.core.spi.component.ioc.IoCProviderFactory.wrap(...)
Run Code Online (Sandbox Code Playgroud)

我已经尝试将MyExceptionMapper放在扫描包层次结构中,以便在初始化期间由SpringServlet拾取,并且在单独的包层次结构中,结果不会更改.

对此的任何帮助或指导将不胜感激.

mSo*_*jic 1

Spring 3.2.3 和 Jersey 2.3.1 集成也遇到了同样的问题。

对我有用的是两者的结合:

  1. 在 app-context xml 中使用注释 jersey@Provider@Service或使其显式为单例

    @Service //implies a singleton-scope
    @Provider
    public class UnhandledExceptionMapper implements ExceptionMapper<Throwable> {
    
        @Override
        public Response toResponse(Throwable exception) { //...
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将包含提供程序类的包添加到球衣包中,我更喜欢在 MyApplication 类中执行此操作:

    public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("com.mycompany.api.controller", "com.mycompany.api.jersey");
                //....
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)