2012-04-13 9 views
2

Springを使用する既存のJava EE Webアプリケーションを更新しています。私のweb.xmlにweb.xmlからspring beanを起動する

は、次のように定義されたサーブレットがあります:

<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は、Application Server (私の場合、weblogic.servlet.internal.WebComponentContributor.getNewInstance ...)によって初期化されます。

so、Springは認識しませんSpringは "myExampleBean"を結ぶチャンスがありません。

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

この初期コードをMyExampleServlet、 に追加する可能性がありますが、servletContextへの参照が必要です。 servletContextへの参照を取得するには?お使いのアプリケーションコンテキストXMLで

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

答えて

0

、あなたが

<bean id="myExampleBean" class="path/to/myExampleBean"> 
+0

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/GenericServlet.html

コード変更を参照してください。問題は、SpringがMyExampleServletのインスタンスを作成していないということです(Springを作成するのはWeblogicです)。したがって、SpringはmyExampleBeanをautowiringしません。 –

2

ようなものが必要私が見る、HttpServletの/ GenericServletからのgetServletContext()メソッド、 (およびアプリケーションサーバは、(のServletConfigサーブレットのinit最初の呼び出しをしていますconfig)、configにはservletContextへの参照が含まれています)。私はすでにこれを持って

class MyExampleServlet extends HttpServlet { 
    MyExampleBean myExampleBean; 

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

    [...] 
} 
関連する問題