2.4 通过ApplicationContext接口获取Spring容器

Spring容器最基本的的接口是BeanFactory,负责配置、创建、管理Bean,称为Spring上下文。它有一个比较重要的子接口:ApplicationContext,大部分时候,我们都采用ApplicationContext实例作为Spring容器,所以这里主要讲通过ApplicationContext获取Spring容器。

ApplicationContext主要的实现类有:

  • FileSystemXmlApplicationContext
  • ClassPathXmlApplicationContext
  • AnnotationConfigApplicationContext
  • XmlWebApplicationContext

FileSystemXmlApplicationContext是从文件绝对路径加载配置文件

ClassPathXmlApplicationContext是从classpath下加载配置文件(适合于相对路径方式加载)

XmlWebApplicationContext在Web应用中使用Spring容器

AnnotationConfigApplicationContext实现基于Java的配置类加载Spring的应用上下文.避免使用application.xml进行配置

具体使用方法可参考:
http://blog.csdn.net/souichiro/article/details/6068552
http://blog.csdn.net/lzx1037922850/article/details/53694951

ApplicationContext主要额外功能:

  • 默认预初始化所有的singleton Bean,可通过为<bean>元素指定lazy-init="true"属性取消预初始化
  • 继承MessageSource接口,提供国际化支持
  • 资源访问,比如访问URL和文件
  • 事件机制,容器事件(ApplicationEvent)和监听器(ApplicationListener)
  • 同时加载多个配置文件
  • 以声明式方式启动并创建Spring容器

主程序只需要一行代码

//ApplicationContext会自动预初始化容器中singleton Bean————包括调用无参数构造器
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");

猜你喜欢

转载自blog.csdn.net/gd_hacker/article/details/76466648
今日推荐