ssm框架整合入门系列——配置Spring applicationContext.xml

版权声明:一起学习咯! https://blog.csdn.net/qq_32953185/article/details/83110400

配置Spring


数据源配置

application.xml添加如下配置,

<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>

src/main/resource目录下添加dbconfig.properties文件,内容:

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.passwordo=admin

对应的,在MySQL下建立专用的数据库ssm_crud,暂且留空

CREATE DATABASE IF NOT EXISTS ssm_crud

applicationContext.xml中引入dbconfig.properties文件,在<bean>标签前添加:
(记得在Namespaces中勾选context)

<context:property-placeholder location="classpath:dbconfig.properties"/>

扫描业务逻辑组件(context:component-scan)
添加:

	<context:component-scan base-package="com.liantao">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

使用exclude-filter,设定除了Controller不要,别的都要。

配置和MyBatis的整合

首先在src/main/resources目录下新建一个mybatis-comfig.xml文件和mapper文件夹
然后,在application.xml添加:

<!-- 配置和mybatis整合 -->
	<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定mybatis全局配置文件的位置 -->
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<property name="dataSource" ref="pooledDataSource"></property>
		<!-- 指定mybatis.mapper文件的位置 -->
		<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
	</bean>

<!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 扫描所有dao接口的实现加入到ioc容器 -->
		<property name="basePackage" value="com.liantao.crud.dao"></property>
	</bean>

事务控制的配置

Namespaces勾选aoptx后,添加:

<!-- 事务控制的配置 -->
	<!-- 需要注意的是,id要和下面事务增强的transaction-manager的值一致,默认为trasactionManager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 控制数据源 -->
		<property name="dataSource" ref="pooledDataSource"></property>
	</bean>
	<!-- 开启基于注解的事务,使用xml配置形式的事务,(必要的重要的都是使用xml配置式的 -->
	<aop:config>
		<!-- 切入点表达式 -->
		<aop:pointcut expression="execution(* com.liantao.crud.service..*(..))" id="txPoint"/>
		<!-- 配置事务增强 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
	</aop:config>
	
	<!-- 配置事务增强,事务如何切入 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 所有方法都是事务方法 -->
			<tx:method name="*"/>
			<!-- 以get开始的所有方法 -->
			<tx:method name="get" read-only="true"/>
		</tx:attributes>
	</tx:advice>

放两篇文章:
事务管理3种配置方式
原理分析

END

猜你喜欢

转载自blog.csdn.net/qq_32953185/article/details/83110400