spring中擷取applicationContext(2)

來源:互聯網
上載者:User

標籤:des   http   java   html   代碼   io   

前幾天寫web項目的時候,用到了spring mvc。

但是又寫bean。我要在代碼裡面產生,而這個bean裡面,又有一些屬性是通過spring注入的。

所以,只能通過ApplicationContext來擷取。

在servlet裡面擷取ApplicationContext其實可以通過spring提供的方法:

?
1 WebApplicationContextUtils.getWebApplicationContext(ServletContext)

來擷取。

這個方法前提是要在web.xml裡面即一個listener:

?
12345678910 <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath:spring-servlet.xml,            classpath:applicationContext.xml        </param-value>    </context-param><listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>

不過這樣子只能在servlet裡面擷取。

如果要在servlet外擷取ApplicationContext呢?

其實可以封裝一下的:

?
12345678910111213141516171819202122232425262728293031323334353637 package me.idashu.code.util; import org.springframework.context.ApplicationContext;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener; /** * 描述:ApplicationContext容器 * * @author: dashu * @since: 13-5-11 */public class AppContext implements ServletContextListener {     private static WebApplicationContext springContext;     public AppContext() {        super();    }     public void contextInitialized(ServletContextEvent event) {        springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());     }      public void contextDestroyed(ServletContextEvent event) {    }     public static ApplicationContext getApplicationContext() {        return springContext;    } }

還需要在web.xml裡面再加條記錄:

?
123 <listener>        <listener-class>me.idashu.code.util.AppContext</listener-class>    </listener>

其實就是在content初始化的時候,把ApplicationContext儲存起來,下次方便調用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.