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>

猜你喜欢

转载自sqcwfiu.iteye.com/blog/2034262