2

Spring を使用する既存の Java EE Web アプリケーションを更新しています。

私の web.xml には、次のように定義されたサーブレットがあります。

  <servlet>
    <display-name>My Example Servlet</display-name>
    <servlet-name>MyExampleServlet</servlet-name>
    <servlet-class>com.example.MyExampleServlet</servlet-class>
  </servlet>

ここで、このクラスに @Autowite アノテーションを追加する必要があります。

class MyExampleServlet extends HttpServlet {
    @Autowired (required = true)
    MyExampleBean myExampleBean;

    [...]
}

問題は、MyExampleBean がアプリケーション サーバーによって初期化されることです (私の場合は weblogic.servlet.internal.WebComponentContributor.getNewInstance...)。

そのため、Spring はそれを認識しておらず、Spring には「myExampleBean」を配線する機会がありません。

それを解決する方法は?つまり、MyExampleServlet が myExampleBean への参照を取得できるように、web.xml または MyExampleServlet をどのように変更する必要があるのでしょうか?

この初期化コードを MyExampleServlet 内に追加することもできますが、それには servletContext への参照が必要です。servletContext への参照を取得するには?

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
myExampleBean = (MyExampleBean) context.getBean("myExampleBean");
4

2 に答える 2

2

なるほど、HttpServlet/GenericServlet には getServletContext() メソッドがあります (アプリケーション サーバーは最初にサーブレットの init(ServletConfig config) を呼び出し、config には servletContext への参照が含まれています)。

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/GenericServlet.htmlを参照してください。

コードが変更されました:

class MyExampleServlet extends HttpServlet {
    MyExampleBean myExampleBean;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        myExampleBean = (MyExampleBean) context.getBean("myExampleBean");
    }

    [...]
}
于 2012-04-13T14:25:26.810 に答える
0

アプリケーションコンテキストxmlでは、次のようなものが必要です

<bean id="myExampleBean" class="path/to/myExampleBean">
于 2012-04-13T13:42:45.377 に答える