重温Spring框架(二、Spring Bean的装备模式之一:Spring IoC容器)

40 篇文章 0 订阅

Spring IoC容器的设计主要基于BeanFactory和ApplicationContext两个接口。

1、Bean工厂BeanFactory【这种加载方式在实际开发中并不多见,了解即可】,语法如下:

        BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("X:/bean.xml"));

2、Bean工厂ApplicationContext,是BeanFactory的子接口之一【相当于BeanFactory是Spring IoC容器所定义的最底层接口,而ApplicationContext是其高级接口之一,所以该方式是常用的】有三个常用的实现类:

  • ApplicationContext ctx = new ClassPathXmlApplicationContext(String configLocation);
  • ApplicationContext ctx = new FileSystemXmlApplicationContext(String configLocation);
  • ServletContextCleaner servletContextCleaner = request.getSession().getServletContext();
    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContextCleaner);

3、Web项目的启动是由相应的Web服务器负责的,因此在Web项目中,ApplicationContext容器的实例化工作交给了Web服务器来完成,为此Spring提供了以下两种方式:

3-1:基于ContextLoaderListener实现:这种方式只适用于Servlete2.4及以上规范的Servlet,需要在web.xml中添加如下代码:

<!--    指定Spring配置文件的位置,多个配置文件以逗号分隔 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--    指定以ContextLoaderListener方式启动Spring容器-->
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

3-2:基于ContextLoaderServlet实现:这种方式只适用于Servlete2.4及以上规范的Servlet,需要在web.xml中添加如下代码:

<!--    指定Spring配置文件的位置,多个配置文件以逗号隔开 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--指定以Servlet方式启动Spring容器-->
<servlet>
    <servlet-name>context</servlet-name>
    <servlet-class>
        org.springframework.web.context.ContextLoaderServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值