Spring中ApplicationContext加载机制

加载器目前有两种选择:ContextLoaderListener和ContextLoaderServlet。
         这两者在功能上完全等同,只是一个是基于Servlet2.3版本中新引入的Listener接口实现,而另一个基于Servlet接口实现。开发中可根据目标Web容器的实际情况进行选择。

配置非常简单,在web.xml中增加:
<listener>
       <listener-class>
          org.springframework.web.context.ContextLoaderListener
       </listener-class>
</listener>
或:
<servlet>
         <servlet-name>context</servlet-name>
         <servlet-class>
           org.springframework.web.context.ContextLoaderServlet
         </servlet-class>
         <load-on-startup>1</load-on-startup>
</servlet>
 


通过以上配置,Web容器会自动加载/WEB-INF/applicationContext.xml初始化
ApplicationContext实例,如果需要指定配置文件 位置,可通过context-param加以指定:
<context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>

配置完成之后,即可通过
WebApplicationContextUtils.getWebApplicationContext方法在Web应用中获取ApplicationContext引用。

如:ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext();
         LoginAction action=(LoginAction)ctx.getBean("action");

-------------------------------------------------------------------------------------------

spring为ApplicationContext提供有三种实现(举例)

         spring为ApplicationContext提供的3种实现分别为:ClassPathXmlApplicationContext, FileSystemXmlApplicationContext 和XmlWebApplicationContext,其中XmlWebApplicationContext是专为Web工程定制的。使用举例如下:
   1. FileSystemXmlApplicationContext
           eg1. ApplicationContext ctx = new FileSystemXmlApplicationContext ("bean.xml"); //加载单个配置 文件
           eg2.
                   String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
                   ApplicationContext ctx = new FileSystemXmlApplicationContext (locations ); //加载

配置文件
           eg3.        

        ApplicationContext ctx =new FileSystemXmlApplicationContext ("D:/project/bean.xml");//根据具体路径加载 文件
   2. ClassPathXmlApplicationContext
           eg1.   ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
           eg2.
                   String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
                   ApplicationContext ctx = new ClassPathXmlApplication(locations);
           注:其中FileSystemXmlApplicationContext 和ClassPathXmlApplicationContext与BeanFactory的xml文件 定位方式一样是基于路径的。
3. XmlWebApplicationContext
       eg1. ServletContext servletContext = request.getSession().getServletContext();    
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
 
注 : 一般是 ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
 
 

以下是详解Spring的applicationContext.xml文件代码:
<!-- 头文件,主要注意一下编码 -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 建立数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <!-- 数据库驱动,我这里使用的是Mysql数据库 -->
   <property name="driverClassName">
    <value>com.mysql.jdbc.Driver</value>
   </property>
   <!-- 数据库地址,这里也要注意一下编码,不然乱码可是很郁闷的哦! -->
   <property name="url">
    <value>
       jdbc:mysql://localhost:3306/tie?useUnicode=true&amp;characterEncoding=utf-8
   </value>
   </property>
   <!-- 数据库的用户名 -->
   <property name="username">
    <value>root</value>
   </property>
   <!-- 数据库的密码 -->
   <property name="password">
    <value>123</value>
   </property>
</bean>
<!-- 把数据源注入给Session工厂 -->
<bean id="sessionFactory"
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource">
    <ref bean="dataSource" />
   </property>
   <!-- 配置映射文件 -->
   <property name="mappingResources">
    <list>
     <value>com/alonely/vo/User.hbm.xml</value>
    </list>
   </property>
</bean>
<!-- 把Session工厂注入给hibernateTemplate -->
<!-- 解释一下hibernateTemplate:hibernateTemplate提供了很多方便的方法,在执行时自动建立 HibernateCallback 对象,例如:load()、get()、save、delete()等方法。 -->

<bean id="hibernateTemplate"
   class="org.springframework.orm.hibernate3.HibernateTemplate">
   <constructor-arg>
    <ref local="sessionFactory" />
   </constructor-arg>
</bean>
<!-- 把DAO注入给Session工厂 -->
<bean id="userDAO" class="com.alonely.dao.UserDAO">
   <property name="sessionFactory">
    <ref bean="sessionFactory" />
   </property>
</bean>
<!-- 把Service注入给DAO -->
<bean id="userService" class="com.alonely.service.UserService">
   <property name="userDAO">
    <ref local="userDAO" />
   </property>
</bean>
<!-- 把Action注入给Service -->
<bean name="/user" class="com.alonely.struts.action.UserAction">
   <property name="userService">
    <ref bean="userService" />
   </property>
</bean>
</beans>

 

下面是Struts+Spring+Hibernate的中 applicationContext.xml配置文件分析

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

<!-- 此配置文件整合了Spring和hibernate的配置文件!采用BasicDataSource注入到hibernate sessionFactory中,以得到数据库连接 -->
<!-- dbcp相关参数配置见 http://marzian.blog.163.com/blog/static/266863120086845013920 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
   <property name="driverClassName">
    <value>oracle.jdbc.driver.OracleDriver</value>
   </property>
   <property name="url">
    <value>jdbc:oracle:thin:@10.18.100.52:1521:dxcp1</value>
   </property>
   <property name="username">
    <value>newgspls</value>
   </property>
   <property name="password">
    <value>newgspls</value>
   </property>
   <property name="initialSize">
    <value>1</value>
   </property>
   <property name="maxActive">
    <value>60</value>
   </property>
   <property name="minIdle">
    <value>1</value>
   </property>
   <property name="maxWait">
    <value>6000</value>
   </property>
   <property name="validationQuery">
    <value>select user from dual</value>
   </property>
    </bean>   
   <!--从连接池中抽取出本地数据库JDBC对象 几种JDBC对象抽取器,可根据不同的应用服务器进行调整
   WebLogic:WebLogicNativeJdbcExtractor
        WebSphere:WebSphereNativeJdbcExtractor
        JBoss:JBossNativeJdbcExtractor
-->
    <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true"></bean>
    
    <!-- s可以使用Spring的 JDBC帮助类 jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource"><ref bean="dataSource"/></property>
    </bean>
    <!--Spring 提供了两种LobHandler 用于处理Blob数据
    DefaultLobHandler:适用于大部分的数据库,如SqlServer,MySQL,对Oracle 10g也适用,但不适用于Oracle9i
oracleLobHandler:适用于Oracle 9i和Oracle 10g。
    -->
    <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true"> 
    <property name="nativeJdbcExtractor"> 
       <ref local="nativeJdbcExtractor" /> 
    </property> 
</bean>
<!--Hibernate Session工厂配置-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource">
            <ref local="dataSource"/>
        </property>
        <property name="lobHandler" ref="lobHandler"/>
        <property name="mappingResources">
            <list>
            <!-- hibernate实体映射文件!即生成的 *.hbm.xml-->                     
     <value>com/dao/hibernate/xml/MaintenanceWork.hbm.xml</value>         
     <value>com/dao/hibernate/xml/SignIn.hbm.xml</value>         
            </list>
        </property>
        <!-- sessionFactory相关配置 -->
        <property name="hibernateProperties">
        <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
           <prop key="hibernate.show_sql">true</prop>
           <!--采用Hibernate2.0的HSql解释器,解决了中文问题-->
           <prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
           <!--打开Query Cache开关,需要Cache的query需要单独配置-->
           <prop key="hibernate.cache.use_query_cache">true</prop>
     <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
        </props>
        </property>
</bean>

<!--事务管理器配置-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
   <property name="sessionFactory">
    <ref local="sessionFactory"/>
   </property>
</bean>
<!--AOP 事务配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
      <!-- the transactional semantics... -->
       <tx:attributes>
           <!-- all methods starting with 'get' are read-only -->
           <tx:method name="get*" read-only="true"/>
           <tx:method name="add*" read-only="false"/>
           <tx:method name="insert*" read-only="false"/>
           <tx:method name="update*" read-only="false"/>
           <tx:method name="del*" read-only="false"/>
           <tx:method name="audit*" read-only="false"/>

           <!-- other methods use the default transaction settings (see below) -->
           <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="SysFileOperation" expression="execution(* com.biz.system.SysFilesBiz.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="SysFileOperation"/>
    </aop:config>
    
    
<!-- jdbc Dao 配置 begion -->
<bean id="jdbcDao" class="com.gsww.newgspls.dao.JdbcDao">
   <property name="ds">
    <ref local="dataSource"/>
   </property> 
</bean>

<!-- 信息发布配置开始 -->
   <bean id="sysInfoBiz" class="com.biz.info.SysInfoBiz">
    <property name="sysInfoDao">
    <ref local="sysInfoDao" /> 
   </property>
    </bean>   
<bean id="sysInfoDao" class="com.dao.info.SysInfoDao">
   <property name="sessionFactory">
    <ref local="sessionFactory"/>
   </property> 
</bean> 
</beans>

### 回答1: SpringApplicationContext是一个接口,它是Spring框架的核心接口之一。它是一个Bean工厂,用于管理应用程序的Bean对象。ApplicationContext提供了一种机制,可以在应用程序轻松地创建、配置和管理Bean对象。它还提供了一些高级功能,如事件发布、国际化、资源加载和AOP等。ApplicationContextSpring框架的核心,它为应用程序提供了依赖注入和面向切面编程等重要功能。 ### 回答2: SpringApplicationContext是一个重要的容器,用于管理Spring应用程序的所有组件,并协调它们之间的协作。它是应用程序的核心,提供了BeanFactory的所有功能,并且还提供了许多其他功能。 一些关键点如下: 1. ApplicationContext使用Spring IoC容器来实现依赖注入:它将组件实例化并将它们注入到实例的其他组件,这使得应用程序更为松散耦合、更容易测试和维护。 2. ApplicationContext是BeanFactory的超集:它包含了所有BeanFactory的功能,并增加了许多其他功能,例如Event Handling、国际化、AOP等。 3. ApplicationContext的生命周期也比BeanFactory更长:它可以管理多个BeanFactory实例,并根据应用程序所需进行必要的配置,从而使Spring应用程序的生命周期更加灵活和可控。 4. ApplicationContext的实现可以是不同的,例如ClassPathXmlApplicationContext、FileSystemXmlApplicationContext等:根据应用程序的需求选择相应的ApplicationContext进行实例化和配置。 总之,ApplicationContextSpring容器的核心组件,提供了Spring应用程序的依赖注入、比BeanFactory更多的功能等,是一个重要的管理和协调组件。 ### 回答3: Spring框架是目前业界使用最为广泛的java开发框架之一,其提供的IOC和AOP功能,让开发人员能够更加轻松的实现开发任务,提高了开发效率,并且更好的维护了代码的可阅读性与灵活性。其ApplicationContextSpring框架的一个重要类,其作用是管理bean的生命周期。 ApplicationContext是一个面向Spring框架的对象容器,其负责创建、初始化和协调bean的创建与之间的关系。它是一个在应用程序运行时用于加载bean定义(配置文件或注解方式等)的类,并将这些bean添加到容器,并在接收到请求时提供这些bean。 ApplicationContext容器可以使用多种不同的实现方式,如XML文件、注解方式等,从而支持各种不同的应用场景。例如,当我们需要在应用动态的加载bean时,就可以使用XML方式来配置容器,当我们需要更加轻量级的容器时,可以使用Annotation方式来实现。无论使用何种方式,所有的bean的定义都是被装配到对应的ApplicationContext容器ApplicationContext对比BeanFactory有很多优势,其主要的优势是使得Spring容器的启动速度更快,可以提供更好的性能以及更好的功能。 ApplicationContext会在容器启动时立即处理所有的Bean定义和之前定义为“懒加载”的Bean,而BeanFactory在使用时才会去解析或懒加载Bean,因此在启动时会比较卡。 总而言之,ApplicationContextSpring框架的一个十分重要的类,它能够管理bean的生命周期,用于加载bean的定义,为应用程序提供Bean的实例,并且提供了很多的功能和优势。学习和了解ApplicationContext的使用方式,对于掌握Spring框架及其相关技术是非常重要的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值