@Context没有在RESTEasy JAX-RS应用程序中注入ServletContext

时间:2017-02-01 21:59:40

标签: java jboss jax-rs resteasy jboss6.x

我正在向JBoss EAP 6.2部署JAX-RS应用程序。 我试图从JAX-RS资源类中获取ServletContext,以便我可以读取我在context-param文件中设置的一些WEB-INF/web.xml值。 即,在我抓住ServletContext之后,我打算致电ServletContext#getInitParam以获取价值。 我正在使用注入按照here ServletContext获取web.xml

我的<servlet> <servlet-name>resteasy-servlet</servlet-name> <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher </servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>foo.MyApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>resteasy-servlet</servlet-name> <url-pattern>/jax-rs/*</url-pattern> </servlet-mapping> 的相关部分是:

MyApplication

所以我使用的是与JBoss捆绑在一起的RESTEasy。

班级public class MyApplication extends Application { private Set<Object> singletons = new HashSet<>(); public MyApplication() { singletons.add( new MyResource() ); } @Override public Set<Object> getSingletons() { return singletons; } } 是:

MyResource

...最后在课堂@Path(...) public class MyResource { @Context ServletContext context; public MyResource() { // I understand context is supposed to be null here } // ... but it should have been injected by the time we reach the service method. @Path("/somePath") @GET @Produces(MediaType.APPLICATION_JSON) public Response someMethod( ) { if (context==null) throw new RuntimeException(); ... } } 中我有以下内容:

RuntimeException

以上代码始终会导致ServletContext被抛出。即RESTEasy以某种方式无法注入context-param。请注意,我没有任何其他JAX-RS问题。即如果我硬编码我希望能够通过`ServletContext#getInitParameter“检索的ServletContext值,那么当WAR部署到JBoss时,JAX-RS休息功能会按预期工作。

进一步尝试我发现@Path("/somePath") @GET @Produces(MediaType.APPLICATION_JSON) public Response someMethod(@Context ServletContext servletContext) { ... } 仅在我在服务方法的参数处执行注入时才会注入:

context-param

...但我不想更改API。此外,我想一劳永逸地执行基于ServletContext值的一些代价高昂的初始化,而不是每次服务方法调用。

我的问题是:

  1. 为什么注射失败?
  2. 我有点厌倦了在运行时魔术失败的注释,有没有办法在不使用注释的情况下获取MyApplication
  3. 或者,我的ServletContext类是否可以获取MyResource并将其作为构造函数参数传递给Class#getResourceAsStream类?
  4. 如果其他所有方法都失败了,我想我总是可以使用Select自行阅读和解析web.xml文件吗?

1 个答案:

答案 0 :(得分:2)

根据链接到this answer的FrAn的评论,这就是我最终做的事情:

public class JaxRsApplication extends Application {

    private Set<Object> singletons = new HashSet<>();

    public JaxRsApplication(@Context ServletContext servletContext) {
        Assert.assertNotNull(servletContext);
        singletons.add( new UserDatabaseResource(servletContext) );
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

...然后,在UserDatabaseResource课程中,我有以下内容:

public UserDatabaseResource(ServletContext servletContext) {
    Assert.assertNotNull(servletContext);
    ...
    String jndiNameForDatasource = servletContext.getInitParameter("whatever")) ;
    ...
}

这作为UserDatabaseResource类,我的DAL层是单例,我只需要获取要使用的数据源的JNDI名称(来自web.xml文件)。但也许这种方法也适用于非单例类的一些小调整。