实例化Spring IoC容器

来源:互联网 发布:ubuntu 怎么安装软件 编辑:程序博客网 时间:2024/04/30 12:29

Spring提供两种IoC容器实现类型:

  • Bean工厂(Beanfactory),对应的接口是BeanFactory
  • 应用程序上下文(Applicationcontext),对应的借口是ApplicationContext,推荐使用。

ApplicationContext接口对应的实现类有:

  • ClassPathXmlApplicationContext:实现从classpath中装入XML配置文件,构建应用程序上下文。
  • FileSystemXmlApplicationContext:实现从文件系统或URL装载XML配置文件。
  • XmlWebApplicationContextXmlPortletApplicationContext:仅能用于Web和入口应用程序。

实例化应用程序上下文

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext*.xml");

IoC容器中得到Bean

为了从Bean工厂或者应用程序上下文中得到已声明的bean,只需要调用getBean()方法并且传递唯一的bean名称。getBean()方法的返回类型为java.lang.Object,在使用之前必须将其转换为实际的类型。

SequenceGenerator generator = (SequenceGenerator) context.getBean("sequenceGenerator");

web项目,根据BeanId获取实体Bean

因为在web.xml中已经使用如下配置实例化应用程序上下文

<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
在java代码中可以使用如下方法获得Bean

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());SequenceGenerator generator = ctx.getBean("sequenceGenerator");
ServletActionContext.getServletContext()struts2提供的方法,获得web上下文信息。

参考文档:Spring 攻略(第 2 版)