Controller内でApplicationContextを取得するには? | Java Springの逆引きメモ

Java Springの逆引きメモ

JavaのSpring frameworkのメモを書いていきます!
初心者の勉強ノートなので間違いがあるかもしれませんが、何かヒントになることがあれば幸いです。

SpringのControler内で指定したbeanを取得するにはどうしたらいいでしょうか。



【Springの派生クラスをextendsしている場合】

実はそれ程難しくないんです!

Springが用意しているControllerの派生クラス(SimpleFormControllerなど)を継承している場合、以下のメソッドがあります。


getApplicationContext()


これで取得できます。


使用例:

(MemberService)getApplicationContext().getBean("memberService");




【SpringMVCのControllerの場合】

SpringのControllerインターフェースを直接implementsしている場合。

以下のようにします。


SpringのWebContentGeneratorクラスをextendsします。

すると、getApplicationContext()を使用できます。




【StrutsのDelegatingActionProxyの派生クラス内でbeanを取得したい場合】

この場合は、以下のように取得します。


使用例:

(MemberService)getWebApplicationContext(getServlet(), mapping.getModuleConfig()).getBean("memberService");



【上記以外 (完全にSpringと関係ないメソッドなどで呼び出したい場合、StrutsのAction)】

この場合、Springと関係する箇所から引数としてApplicationContextを引き回した方がいいかもしれません。

でも、一応、そのまま取得する方法を書いておきますね。

WebApplicationContextUtilsを使用します。

ServletContextが必要なので、どこかで適当に取得してから、使用します。


使用例:

ServletContext context = request.getSession().getServletContext();


WebApplicationContext wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(context);


(MemberService)wac.getBean("memberService");


どうです?

うまく取得できました?



参照:

・トップ

・SpringMVCの機能について

・Controller内でApplicationContextを取得するには?

・リクエストの文字コードを設定ファイルで制御するには?

・SpringMVCを使用してWEBを作るには? (基礎編)

・Validatorでパラメタの妥当性チェックをするには?

・SpringMVCを使用してWEBを作るには? (実践編) : (パラメタとオブジェクトのバインドの方法)

・tilesについて