ssm框架整合入門系列——配置Spring applicationContext.xml
阿新 • • 發佈:2018-11-03
配置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
勾選aop
和tx
後,新增:
<!-- 事務控制的配置 -->
<!-- 需要注意的是,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