1.Spring数据库的配置
<!-- Spring的Hibernate工具类HibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" scope="singleton">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" scope="singleton">
<property name="driverClassName"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver">
</property>
<property name="url"
value="jdbc:sqlserver://localhost:1433;databaseName=csu">
</property>
<property name="username" value="liky"/>
<property name="password" value="redhat"/>
</bean>
<!-- Spring的声明式事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置事务的传播特性,通常应该将事务设置在业务层,而非dao上 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- name为事务对哪些方法生效,可以使用通配符; propagation为事务的传播特性,一共有6种-->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切入点,就是哪些包的哪些类的哪些方法参与事务 -->
<aop:config>
<!-- id是一个标识,expression中的execution表达式比较复杂:
1.第一个星号表示匹配所有的返回值;2.abu.csdn.service表示包;3.第二个星号表示匹配这个包的所有类
4.第三个星号表示匹配类的所有方法;5.括号内表示方法的参数;6.两个点表示匹配所有的参数
-->
<aop:pointcut id="allServiceMethods"
expression="execution(* abu.csdn.service.*.*(..))" />
<!-- 指定事务和切入点 -->
<aop:advisor pointcut-ref="allServiceMethods"
advice-ref="txAdvice" />
</aop:config>
</beans>
2.Servlet
/**
* <p>
* 在Servlet中注入对象的步骤:
* 1.取得ServletContext
* 2.利用Spring的工具类WebApplicationContextUtils得到WebApplicationContext
* 3.WebApplicationContext就是一个BeanFactory,其中就有一个getBean方法
* 4.有了这个方法就可像平常一样为所欲为了,哈哈!
* </p>
*/
@Override
public void init() throws ServletException {
super.init();
ServletContext servletContext = this.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
hibernateTemplate = (HibernateTemplate)ctx.getBean("hibernateTemplate");
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
3.总结
你应该看到了,我在Spring中使用了声明式事务,如果直接使用Spring的工厂类在这里是不行的,因为所有的对象都已经有Spring的IoC管理了,所以只能借助WebApplicationContextUtils这个工具类来获得Bean.