Spring配置文件各个属性详解

本博中关于Spring的文章:Spring IOC和AOP原理Spring事务原理探究Spring配置文件属性详解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&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配置文件分析

注意关于声明式事务的AOP配置要使用tx:advice, 这个标签有特殊的格式:

默认的 <tx:advice/> 设置如下:

  • 事务传播设置是 REQUIRED

  • 隔离级别是 DEFAULT

  • 事务是 读/写

  • 事务超时默认是依赖于事务系统的,或者事务超时没有被支持。

  • 任何 RuntimeException 将触发事务回滚,但是任何 checked Exception 将不触发事务回滚

这些默认的设置当然也是可以被改变的。 <tx:advice/> 和 <tx:attributes/> 标签里的 <tx:method/> 各种属性设置总结如下:

属性 是否需要? 默认值 描述
name  

与事务属性关联的方法名。通配符(*)可以用来指定一批关联到相同的事务属性的方法。 如:'get*''handle*''on*Event'等等。

propagation REQUIRED 事务传播行为
isolation DEFAULT 事务隔离级别
timeout -1 事务超时的时间(以秒为单位)
read-only false 事务是否只读?
rollback-for  

将被触发进行回滚的 Exception(s);以逗号分开。 如:'com.foo.MyBusinessException,ServletException'

no-rollback-for  

 被触发进行回滚的 Exception(s);以逗号分开。 如:'com.foo.MyBusinessException,ServletException'


<?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>

整合Hibernate的在上面XML中的配置SessionFactory的时候就已经将Hibernate整合到Spring中来了,在此Bean中的有一个属性为MappingResource的list中可以列出所有的hbm映射文件。


一、引用外部属性文件

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
    <value>classpath:mail.properties</value>
    <value>classpath:jdbc.properties</value>
   </list>
  </property>
 </bean>

我们定义了一个PropertyPlaceholderConfigurer类的实例,并将其位置属性设置为我们的属性文件。该类被实现为Bean工厂的后处理器,并将使用定义在文件中的属性来代替所有的占位符(${...}value)。

注意:

而在spring2.5的版本中提供了一种更简便的方式,如:

 
 
  1. <context:property-placeholder location="classpath:config/jdbc.properties"/> 

这样以后要使用属性文件中的资源时,可以使用${属性名}来获得。

 

二、常用数据源的配置

第一种是:DBCP数据源,(需要加入2个jar文件,在spring中的lib下jakarta-commons/commons-dbcp.jar和commons-pools.jar)主要配置如下:

<!-- Mysql版 -->
 <bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName"
   value="com.mysql.jdbc.Driver">
  </property>
  <property name="url"
   value="${jdbc.url}">

  </property>
  <property name="username" value="${jdbc.username}"></property>
  <property name="password" value="${jdbc.password}"></property>
 </bean>

 

第二种是:c3p0数据源,跟第一种一个类型,需加入c3p0.jar包。
第三种是:JNDI数据源,配置在高性能的应用服务器(如WebLogic、WebSphere等)

 

 
 
  1. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
  2.       <property name="jndiName" value="java:comp/env/jdbc/bbt"/> 
  3.   </bean> 

 

从spring2.0开始提供jee命名空间,可以简化配置如下:

  1. <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/bbt"/> 

 

三、配置事务管理器


1、Spring JDBC 和 iBatis事务管理器的配置, 这种事务管理器没有使用hibernate

<!-- 配置事务管理器 -->

 <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="dataSource" />
 </bean>

2、Hibernate3以上事务管理器的配置(先要集成hibernate,再配置事务管理器)
 
 
  1. <!-- 集成hibernate --> 
  2.  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 
  3.     <property name="dataSource" ref="dataSource"/> 
  4.     <property name="mappingResources"> 
  5.       <list> 
  6.         <value>classpath:product.hbm.xml</value> 
  7.       </list> 
  8.     </property> 
  9.     <property name="hibernateProperties"> 
  10.       <props> 
  11.        <prop key="hibernate.dialect"> 
  12.       </props> 
  13.     </property> 
  14.   </bean> 
  15.  
  16. <!-- 配置Hibernate事务策略 --> 
  17.  <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
  18.         <property name="sessionFactory" ref="sessionFactory"></property> 
  19.  </bean> 
3、配置tx/aop声明式事务

    <!-- 声明一个切面 --> 

<tx:advice id="txAdvice" transaction-manager="txManager"> 
  <tx:attributes> 
   <tx:method name="find*" propagation="REQUIRED" read-only="true"/> 
   <tx:method name="save*" propagation="REQUIRED"/> 
   <tx:method name="update*" propagation="REQUIRED"/> 
   <tx:method name="*" propagation="SUPPORTS" read-only="true" /> 
  </tx:attributes> 
 </tx:advice> 

别的例子,可以进行对比下:

<tx:advice id="userTxAdvice" transaction-manager="TransactionManager">
    <tx:attributes>
      <tx:method name="delete*" propagation="REQUIRED" read-only="false" 
                            rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/>

      <tx:method name="insert*" propagation="REQUIRED" read-only="false"
                            rollback-for="java.lang.RuntimeException" />

      <tx:method name="update*" propagation="REQUIRED" read-only="false"
                            rollback-for="java.lang.Exception" />
      
      <tx:method name="find*" propagation="SUPPORTS"/>
      <tx:method name="get*" propagation="SUPPORTS"/>
      <tx:method name="select*" propagation="SUPPORTS"/>
    </tx:attributes>
  </tx:advice>

<!-- 把切面注入到业务中 -->

<aop:config> 
  <aop:pointcut id="productServiceMethods" expression="execution(* com.wzc.student.business.*.*(..))" /> 
  <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods" /> 
 </aop:config> 
 <aop:config>    
    <aop:pointcut id="pc" expression="execution(public * com.haso.bscsserver.service.*.*(..))" /> <!--把事务控制在Service层-->
    <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
  </aop:config>


四、context:component-scan

<!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
 <context:component-scan base-package="com.haso.bscsserver">
  <!-- 允许定义过滤器将基包下的某些类纳入或排除
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->
 </context:component-scan>


 请参考http://blog.csdn.net/ydwuli06/article/details/6993219,具体的自己还深入研究过


五、aop注解支持

<!-- aop注解支持 -->
 <aop:aspectj-autoproxy proxy-target-class="true"/>

 

六、缓存配置

只要在Spring的xml中配置EhCacheBean即可,然后在configLocation指定配置路径

 <bean id="cacheManager"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="/WEB-INF/ehcache.xml"/>
 </bean>
 <!-- A facade to the Ehcache cache class -->
 <bean id="cacheProviderFacade" class="org.springmodules.cache.provider.ehcache.EhCacheFacade">
     <property name="cacheManager" ref="cacheManager" />
 </bean>
ehCache内容及说明如下:

  •     name:Cache的唯一标识  
  •     maxElementsInMemory:内存中最大缓存对象数  
  •     maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大  
  •     eternal:Element是否永久有效,一但设置了,timeout将不起作用  
  •     overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中 
  •     timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大 
  •     timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大  
  •     diskPersistent:是否缓存虚拟机重启期数据  
  •     diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒 
  •     diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区 
  •      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)  
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 <defaultCache overflowToDisk="true" eternal="true"/>
 <diskStore path="C:/cache" />
  <cache name="zzugxy" overflowToDisk="true" eternal="false"  
        timeToIdleSeconds="300" timeToLiveSeconds="600" maxElementsInMemory="1000" 
        maxElementsOnDisk="10" diskPersistent="true" diskExpiryThreadIntervalSeconds="300" 
        diskSpoolBufferSizeMB="100" memoryStoreEvictionPolicy="LRU" />  
</ehcache>

或者使用注解缓存的配置:

关于spring实现ehcache有很多方法,很多都是利用aop来实现,我认为采用注解的方式更灵活,配置也更简洁。所谓注解的方式就应该是一些tag,如tx:advice,下面就是我利用spring-modules-0.9实现的注解缓存。配置文件如下:

<?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:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-2.5.xsd  
           http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
           http://www.springframework.org/schema/tx   
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
           http://www.springmodules.org/schema/ehcache  
           http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">  
         
    <ehcache:config configLocation="classpath:ehcache.xml"/>   
    <ehcache:annotations>   
    <ehcache:caching id="testCache" cacheName="testCache" />   
    <ehcache:flushing id="testFlush" cacheNames="testCache"/>   
    </ehcache:annotations>       
</beans>    
 
这里一定要注意:

    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"

    http://www.springmodules.org/schema/ehcache        

    http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd


七、

<!-- Spring、MyBatis的整合,需要在 Spring 应用上下文中定义至少两样东西:一个SqlSessionFactory和至少一个数据映射器类(UserMapper->iocContext.xml)。 -->
 <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="configLocation" value="classpath:SqlMapConfig.xml" />
  <property name="dataSource" ref="dataSource" />
 </bean>


转载:http://blog.csdn.net/snn1410/article/details/7846582









  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值