2012-04-13 133 views
2

我正在更新使用Spring的現有Java EE Web應用程序。從web.xml初始化spring bean

在我的web.xml,有一個定義爲一個servlet如下:

<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沒有意識到t帽子,Spring並沒有機會連接「myExampleBean」。

如何解決? 也就是說,我需要如何修改web.xml或MyExampleServlet,以便MyExampleServlet獲取對myExampleBean的引用?

可能會在MyExampleServlet中添加此代碼, 但它需要對servletContext的引用。如何獲得對servletContext的引用?

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

回答

0
在您的應用程序上下文XML

,你需要像

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

我已經有這個。問題在於Spring沒有創建MyExampleServlet實例(它是Weblogic創建它的實例),所以Spring不會自動裝配myExampleBean。 – 2012-04-13 13:45:41

2

我看,HttpServlet的/ GenericServlet類具有的getServletContext()方法, (和應用服務器首先調用servlet的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"); 
    } 

    [...] 
}