spring中获取applicationContext(2)

时间:2023-03-09 08:54:38
spring中获取applicationContext(2)

前几天写web项目的时候,用到了spring mvc。

但是又写bean。我要在代码里面生成,而这个bean里面,又有一些属性是通过spring注入的。

所以,只能通过ApplicationContext来获取。

在servlet里面获取ApplicationContext其实可以通过spring提供的方法:

1
WebApplicationContextUtils.getWebApplicationContext(ServletContext)

来获取。

这个方法前提是要在web.xml里面即一个listener:

1
2
3
4
5
6
7
8
9
10
<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呢?

其实可以封装一下的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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里面再加条记录:

1
2
3
<listener>
        <listener-class>me.idashu.code.util.AppContext</listener-class>
    </listener>

其实就是在content初始化的时候,把ApplicationContext保存起来,下次方便调用。