一、需要的jar包
这里使用的是Myeclipes自带的Spring支持
选中的是mybatis和spring整合需要用到的jar包,另外的是 : 日志包 mybatis包 数据库连接用到的包
二、配置文件
applicationContext.xml是spring核心控制文件
database.properties 是数据库连接文件
log4j.properties 是日志配置文件
mybatis-config.xml 是mybatis配置文件(不需要的话可以省略)
还有必不可少的 sql语句映射文件:
application文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- 启用扫描注解 扫描service包下的注解 自动生成bean-->
<context:component-scan base-package="service"></context:component-scan>
<!-- 引入 数据库配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties"></property>
</bean>
<!-- 创建数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="url" value="${address}"></property>
<property name="driverClassName" value="${driver}"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启用注解事务 无需进行 事物增强配置了 但是需要对方法或类进行事物注解 才能启用事物 -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- 配置 sqlsessionFactory -->
<bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- 根据basePackage的位置产生该位置上的所有mappe接口的实现类,配置成spring中的bean -->
<!-- 无需手动创建 xxMapper.java 接口的实现类(对数据库的操作) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper"></property>
</bean>
</beans>
service文件配置
@service 表示自动生成一个 id为 userServiceImpl类型的bean
@Autowired 表示自动匹配 对应类型的bean自动装填
@Transactional(propagation=Propagation.REQUIRED) 在方法或类名上声明事务
在测试类 用ApplicationContext ac=new ClassPathXmlApplicationContext(“applicationContext.xml”);
UserService userService =(UserService) ac.getBean(“userServiceImpl”);
获取业务层接口的实例