標籤: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儲存起來,下次方便調用。