采用这种方式的配置时候,配置文件的增加非常快,每个bean有需要两个bean配置,一个目标,另外还需要使用TransactionProxyFactoryBean配置一个代理bean。
这是一种最原始的配置方式,下面是使用TransactionProxyFactoryBean的配置文件:
- xml version="1.0" encoding="gb2312"?>
-
-
- "http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
-
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
-
- <property name="driverClassName"><value>com.mysql.jdbc.Drivervalue>property>
-
- <property name="url"><value>jdbc:mysql://localhost:3306/springvalue>property>
-
- <property name="username"><value>rootvalue>property>
-
- <property name="password"><value>32147value>property>
- bean>
-
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
-
- <property name="dataSource"><ref local="dataSource"/>property>
- <property name="mappingResources">
- <list>
-
- <value>Person.hbm.xmlvalue>
- list>
- property>
- <property name="hibernateProperties">
- <props>
- <!--此处用来定义hibernate的SessionFactory的属性:
- 不同数据库连接,启动时选择create,update,create-drop-->
- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
- <prop key="hibernate.hbm2ddl.auto">updateprop>
- props>
- property>
- bean>
-
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
-
- <property name="sessionFactory"><ref local="sessionFactory"/>property>
- bean>
-
- <bean id="personDaoTarget" class="lee.PersonDaoHibernate">
-
- <property name="sessionFactory"><ref local="sessionFactory"/>property>
- bean>
-
- <bean id="personDao" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
-
- <property name="transactionManager"><ref bean="transactionManager"/>property>
-
- <property name="transactionAttributes">
- <props>
-
- <prop key="find*">PROPAGATION_REQUIRED,readOnlyprop>
- <!-- 其他方法,采用required的事务策略 ->
- <prop key="*">PROPAGATION_REQUIREDprop>
- props>
- property>
-
- <property name="target">
- <ref local="personDaoTarget"/>
- property>
- bean>
- beans>
在上面的配置文件中,personDao需要配置两个部分,一个是personDao的目标bean,该目标bean是实际DAO bean,以实际的DAO bean为目标,建立事务代理。一个组件,需要来个bean组成,一个目标bean,一个事务代理。
这种配置方式还有一个坏处:目标bean直接暴露在Spring容器中,可以直接引用,如果目标bean被误引用,将导致业务操作不具备事务性。
为了避免这种现象,可将目标bean配置成嵌套bean,下面是目标bean和事务代理的配置片段:
-
- <bean id="personDao" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
-
- <property name="transactionManager"><ref bean="transactionManager"/>property>
-
- <property name="transactionAttributes">
- <props>
-
- <prop key="find*">PROPAGATION_REQUIRED,readOnlyprop>
- <!-- 其他方法,采用required的事务策略 ->
- <prop key="*">PROPAGATION_REQUIREDprop>
- props>
- property>
-
- <property name="target">
-
- <bean class="lee.PersonDaoHibernate">
-
- <property name="sessionFactory"><ref local="sessionFactory"/>property>
- bean>
- property>
- bean>
[@more@]
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/780813/viewspace-1010103/
,如需转载,请注明出处,否则将追究法律责任。