在项目中获取Spring的Bean的几种方式

本文介绍三种在Spring框架中获取ApplicationContext的方法:通过WebApplicationContextUtils工具类、XmlBeanFactory工厂类及直接初始化ApplicationContext对象。

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的情况。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值