【问题标题】:RESTEasy Guice ProviderRESTEasy Guice 提供程序
【发布时间】:2016-08-02 00:40:32
【问题描述】:

我在尝试将 Guice 与 ContainerRequestFilter 一起使用时遇到了一个小问题,它会引发 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);
        }
    }
}

我已将过滤器添加到我的应用程序类中:

@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;
    }
}

我的 Guice 配置:

public class GuiceConfigurator implements Module {
    public void configure(final Binder binder) {
        binder.bind(Dependency.class);
    }
}

我的 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>

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

任何帮助将不胜感激。

【问题讨论】:

    标签: java guice resteasy


    【解决方案1】:

    似乎即使使用 RESTeasy/JAX-RS 组件,您仍然需要使用 Guice binder 注册它。一开始我并不确定,但看看test cases,似乎我们仍然需要向 Guice 注册我们的资源和提供者才能使其正常工作。

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

    public class GuiceConfigurator implements Module {
        public void configure(final Binder binder) {
            binder.bind(MyFilter.class);
            binder.bind(Dependency.class);
        }
    }
    

    为了测试,我关闭了example from the RESTeasy project,添加了一个带有构造函数注入的过滤器,并将过滤器添加到模块绑定器中。并且在将过滤器添加到模块时有效,未添加时失败。

    【讨论】:

    • “RESTEasy 与 Guice 3.0 进行了一些简单的集成。RESTEasy 将扫描绑定类型以查找 Guice 模块的路径和提供者注释。它将向 RESTEasy 注册这些绑定。” (docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html/…)。换句话说,是的,你必须绑定它们。
    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多