1. 方式一 通过Spring提供的工具类获取ApplicationContext对象
org.springframework.context.ApplicationContext ac2 = org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Person Person= (Person) ac2.getBean("Person");
Person.printStr();
这个方式,我们最主要是得到 javax.servlet.ServletContext 对象
如果这个对象在servlet 环境中当然很好得,如果不是的,那我就需要创造这个环境,java B/S项目,只有在web容器中
我们就有办法做到 :
看下面的:
我需要在spring的bean中直接获取,这下可和我们常规的操作有些不同,因为spring的bean都是pojo的。根本见不着servletconfig和servletcontext的影子。
这里我需要指出spring给我们提供了两个接口:org.springframework.web.context.ServletContextAware和
org.springframework.web.context.ServletConfigAware。我们可以让我们的bean实现上边的任何一个接口就能获取到servletContext了 .
代码如下:
public class DicBean implements ServletContextAware{
private ServletContext servletContext;
public void setServletContext(ServletContext sc) {
this.servletContext=sc;
System.out.println("项目的绝对路径为:"+servletContext.getRealPath("/"));
}
}
如果在struts2的action中,我们也可以用下面的:
javax.servlet.ServletContext servletContext = org.apache.struts2.ServletActionContext.getServletContext();
2.方式二 很直接
//以
org.springframework.core.io.ClassPathResource isr = new ClassPathResource("applicationContext.xml");
XmlBeanFactory factory = new XmlBeanFactory(isr);
Person Person= (Person) factory.getBean("Person");
Person.printStr();
3.试下
在初始化时保存ApplicationContext对象
代码:
ApplicationContext ac = new FileSystemXmlApplicationContex("applicationContext.xml");
ac.getBean("beanId");
说明:
这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。