JBoss EAP 6.2にJAX-RSアプリケーションをデプロイします。 ServletContext
をJAX-RSリソースクラスの内部から取得しようとしています。WEB-INF/web.xml
ファイルに設定したcontext-param
の値を読み取ることができます。 私はServletContext
を手に入れた後、ServletContext#getInitParam
に電話をかけて値を取得する予定だった。 注射を使用してServletContext
をhereとしてアドバイスしています。RESTEasy JAX-RSアプリケーションで@Contextが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>
だから私は、JBossに同梱されたRESTEasyを使用しています。
クラスMyApplication
は次のとおりです。
public class MyApplication extends Application {
private Set<Object> singletons = new HashSet<>();
public MyApplication() {
singletons.add(new MyResource());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
&hellip;そして最後に、クラス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
になります。私。 RESTEasyはどうにかしてServletContext
を注入できません。他のJAX-RSの問題はありません。私。私は `のServletContext#getInitParameter」を介して取得することができるように期待していたcontext-param
値をハードコーディングした場合に予想されるようにWARをJBossへデプロイされたとき、その後、JAX-RS残りの機能が動作します。
さらに私はServletContext
ことを発見試します私はこのようなサービスのメソッドの引数で注入を実行した場合にのみ注入される:
@Path("/somePath")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response someMethod(@Context ServletContext servletContext) {
...
}
&hellip;しかし、私はAPIを変更しないことを好むだろう。また、私はに基づいて、いくつかの高価な初期化を実行したいと思います。 context-param
値は1回であり、すべてのサービスメソッド呼び出しではありません。
私の質問は以下のとおりです。
- 理由注入が失敗していますか?
- 私は、実行時に失敗するアノテーションの魔法に少し疲れました。アノテーションを使わずに
ServletContext
を取得する方法はありますか? - また、
MyApplication
クラスはServletContext
を取得し、それをコンストラクタパラメータとしてMyResource
クラスに渡すことはできますか? - 他のすべてがうまくいかない場合、私は常に
Class#getResourceAsStream
を使ってweb.xmlファイルを読み込んで解析できますか?
http://stackoverflow.com/questions/1814517/get-servletcontext-in-jax-rs-resource?noredirect=1&lq=1 – gladiator
@gladiator私の質問では、その回答に具体的にリンクしています。オープニングパラグラフ) –
これをチェック:http://stackoverflow.com/questions/5434667/rest-easy-and-init-params-how-to-access – FrAn