RESTEasy Guice提供商

jma*_*ony 7 java guice resteasy

我在尝试使用带有ContainerRequestFilter的Guice时遇到一个小问题,它会抛出一个NullPointerException.我对RESTEasy进行了一些挖掘,看起来由于@Context注释不存在而无法找到MyFilter的构造函数,因此在尝试实例化null构造函数时会抛出NullPointerException.

我的过滤器:

@Provider
@PreMatching
public class MyFilter implements ContainerRequestFilter {
    private Dependency d;

    @Inject
    public MyFilter(Dependency d) {
        this.d = d;
    }

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        if (d.doSomething()) {
            Response r = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
            containerRequestContext.abortWith(r);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经将过滤器添加到我的Application类:

@ApplicationPath("")
public class Main extends Application {
    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> c = new HashSet<Class<?>>();

    public Main() {
        c.add(Dependency.class);
    }

    @Override
    public Set<Class<?>> getClasses() {
        return c;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Guice配置:

public class GuiceConfigurator implements Module {
    public void configure(final Binder binder) {
        binder.bind(Dependency.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>My App</display-name>

    <context-param>
        <param-name>resteasy.guice.modules</param-name>
        <param-value>com.example.GuiceConfigurator</param-value>
    </context-param>

    <listener>
        <listener-class>
          org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
        </listener-class>
    </listener>
</web-app>
Run Code Online (Sandbox Code Playgroud)

此配置用于将依赖项注入资源,但在尝试在提供程序上使用它时会出现NullPointerException.

任何帮助,将不胜感激.

Pau*_*tha 4

看来即使使用 RESTeasy/JAX-RS 组件,您仍然需要使用 Guice 绑定器注册它。一开始我并不确定,但是看看测试用例我们似乎仍然需要向 Guice 注册我们的资源和提供程序才能使其正常工作。

我在将过滤器添加到 Guice 模块后对其进行了测试,它按预期工作。

public class GuiceConfigurator implements Module {
    public void configure(final Binder binder) {
        binder.bind(MyFilter.class);
        binder.bind(Dependency.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了进行测试,我放弃了RESTeasy 项目中的示例,添加了带有构造函数注入的过滤器,并将过滤器添加到了模块绑定器中。当将过滤器添加到模块时它可以工作,而当不添加过滤器时它会失败。