SpringMVC,Spring,Mybatis整合中Spring配置

2025-11-14 06:53:43

1、新建一个属性文件dbconfig.properties

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.user=root

jdbc.password=root

SpringMVC,Spring,Mybatis整合中Spring配置

2、在application.xml中引入该配置文件

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

SpringMVC,Spring,Mybatis整合中Spring配置

3、配置数据源c3p0,增加一个属性文件dbconfig.properties

<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="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>

SpringMVC,Spring,Mybatis整合中Spring配置

4、配置扫描业务逻辑组件,并且不要扫描控制器

<context:component-scan base-package="com.gwolf">

        <context:exclude-filter type="annotation" 

        expression="org.springframework.stereotype.Controller"/>

        </context:component-scan>

SpringMVC,Spring,Mybatis整合中Spring配置

5、创建一个mybatis全局配置文件:mybatis-config.xml

SpringMVC,Spring,Mybatis整合中Spring配置

6、配置与mybatis的整合

<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean">

        <!-- 指定mybatis全局配置文件的位置 -->

        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <property name="dataSource" ref="comboPooledDataSource"></property>

       

        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>

        </bean>

SpringMVC,Spring,Mybatis整合中Spring配置

7、配置扫描器,将mybatis接口的实现加入到ioc容器中

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <property name="basePackage" value="com.gwolf.crud.dao"></property>

        </bean>

SpringMVC,Spring,Mybatis整合中Spring配置

8、事务控制的配置

<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" 

        id="dataSourceTransactionManager">

        <property name="dataSource" ref="comboPooledDataSource"></property>

        </bean>

        <aop:config>

        <aop:pointcut expression="execution(* com.gwolf.crud.service..*(..))" 

        id="txPoint"/>

        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>

        </aop:config>

        <!-- 配置事务如何切入 -->

        <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">

        <tx:attributes>

        <!-- 所有方法都是事务方法 -->

        <tx:method name="*"/>

        <tx:method name="get*" read-only="true"/>

        </tx:attributes>

        </tx:advice>

SpringMVC,Spring,Mybatis整合中Spring配置

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢