[b] Spring获取ApplicationContext的正确方式[/b]
首先在web.xml里配置ApplicationContext
java程序中:
前提是要获取request或者Servlet
一些遗留系统中我们要获取Bean采用如下方式:
建一个类实现ApplicationContextAware接口,有一个引用ApplicationContext的静态成员,然后,遗留系统需要引用spring管理的bean的地方,使用这个类。
在ApplicationContext中添加:
然后在类中直接调用
首先在web.xml里配置ApplicationContext
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>java程序中:
ServletContext servletContext = request.getSession.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);前提是要获取request或者Servlet
一些遗留系统中我们要获取Bean采用如下方式:
建一个类实现ApplicationContextAware接口,有一个引用ApplicationContext的静态成员,然后,遗留系统需要引用spring管理的bean的地方,使用这个类。
public class SpringContext implements ApplicationContextAware {
protected static ApplicationContext context;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
public static Object getBean(String name){
return getContext.getBean(name);
}
}在ApplicationContext中添加:
<bean id="springContext" class="net.blogjava.chenlb.SpringContext"></bean>然后在类中直接调用
SpringContext.getBean("name");
本文介绍在Spring框架中正确获取ApplicationContext的方法。通过配置web.xml并利用ContextLoaderListener, 可以在Java程序中轻松访问ApplicationContext。此外,还提供了一种通过创建自定义类实现ApplicationContextAware接口来获取Bean的方式。
1535

被折叠的 条评论
为什么被折叠?



