When I wrote a Web project a few days ago, spring MVC was used.
But write beans again. I'm going to generate it in the code, and in this bean, some of the attributes are injected through spring.
Therefore, it can only be obtained by ApplicationContext.
Getting ApplicationContext in a servlet can actually be done through spring:
?
| 1 |
WebApplicationContextUtils.getWebApplicationContext(ServletContext) |
To get.
The premise of this method is to have a listener in Web. XML:
?
| 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> |
But this can only be obtained in the servlet.
What if you want to get ApplicationContext out of a servlet?
In fact can be encapsulated:
?
| 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; }} |
Also need to add a record in the Web. xml:
?
| 123 |
<listener> <listener-class>me.idashu.code.util.AppContext</listener-class> </listener> |
In fact, when the content is initialized, save the ApplicationContext, the next convenient call.