我正在向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
值的一些代价高昂的初始化,而不是每次服务方法调用。
我的问题是:
MyApplication
?ServletContext
类是否可以获取MyResource
并将其作为构造函数参数传递给Class#getResourceAsStream
类?Select
自行阅读和解析web.xml文件吗?答案 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
文件)。但也许这种方法也适用于非单例类的一些小调整。