SpringMVC4 + Spring + MyBatis3 基于注解的最简配置
本文使用最新版本(4.1.5)的springmvc+spring+mybatis,采用最间的配置方式来进行搭建。
1. web.xml
我们知道springmvc是基于Servlet: DispatcherServlet来处理分发请求的,所以我们需要先在web.xml文件中配置DispatcherServlet,而Spring的启动则是使用了监听器,所以需要配置spring的监听器:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>sp</display-name> <servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param> </web-app>
servlet下面的init-param中的指定了springmvc的dispatcherServlet的配置文件:config/spring-mvc.xml,所有springmvc相关的都在该文件中进行配置。在DispatcherServlet(其父类)中使用:getServletConfig().getInitParameter("paramName"); 可以访问到init-param中指定的参数,从而可以读取到config/spring-mvc.xml文件。load-on-startup值为1指定了dispatcherServlet随servlet容器启动。
ContextLoaderListener是spring监听servlet容器的启动的,在servlet容器启动时,就初始化bean工厂,对bean进行初始化等等操作。context-param指定了spring的配置文件config/applicationContext.xml,可以使用: getServletContext().getInitParameter("paraName"); 读取到值。
注意:init-param 和 context-param 的区别,从名字上就可以看得出,后者是相对于整个web应用的,而前者是针对单个servlet的。
2. springmvc.xml
下面我们看一下springmvc.xml该如何配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <mvc:annotation-driven />
<context:component-scan base-package="net.aazj.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
// ... ...
</beans>
启用注解驱动来扫描controller,并指定control的包路径,还有指定了视图解析器,so easy。
注:这里要特别注意,springmvc和spring的配置文件中都有context:component-scan,一个是扫描controller,一个时扫描service,在指定扫描路径时最好不要一样,不要让他们交叉扫描,不然会导致事务不能回滚的错误。如果一定要一样的话那么可以使用如下配置来进行排除:
<!-- springmvc的配置文件中不扫描带有@Service注解的类 -->
<context:component-scan base-package="net.aazj">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!-- spring的配置文件中不扫描带有@Controller注解的类 -->
<context:component-scan base-package="net.aazj">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
3. applicationContext.xml
spring中相关bean扫描,事物的配置,以及和mybatis的结合配置如下所示:
<?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: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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="net.aazj.service" />
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config/db.properties" /> <!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:config/mappers/**/*.xml" />
</bean> <!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" /> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="net.aazj.mapper" />
</bean>
</beans>
同样相关service bean也使用基于注解的扫描方式:context:component-scan,事务也使用注解来驱动:tx:annotation-driven,所以需要在serviceImpl相关类上和方法上使用@Transanctional注解类配置事物。
sqlSessionFactory的配置相当重要,configLocation指定了mybatis的配置文件,如果需要在mybatis配置文件中配置比如<settings>, <typeAliases>, <mappers>则,需要在这里指定,如果不需要就没有必要指定值了。mapperLocations指定了mapper接口映射sql语句的xml文件的位置。MapperScannerConfigurer指定了mapper接口所在的包路径。
4. mybatis-config.xml
spring和mybatis的接口,其实可以不需要mybatis-config.xml文件的存在,只有在需要配置<settings>, <typeAliases>, <mappers>(其实mapper也一并也是在applicationContext.xml中进行配置)才需要mybatis-config.xml文件的存在:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<typeAliases>
<package name="net.aazj.pojo"/>
</typeAliases>
</configuration>
<settings>指定了数据库操作相关的设置,typeAliases指定了可以给数据库表对应的类所在的包路径,可以在sql的xml使用它们的别名:
package net.aazj.pojo;
import org.apache.ibatis.type.Alias;
@Alias("User")
public class User {
private Integer id;
private String name;
// ... ...
}
@Alias("User")注解了该pojo的别名,所以可以在xml文件中使用别名 User 来代替:net.aazj.pojo.User
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.aazj.mapper.UserMapper">
<cache /> <select id="getUser" resultType="User">
select * from user where id = #{id}
</select> <select id="addUser" parameterType="string">
insert into user(name) values(#{name})
</select>
</mapper>
这里 resultType="User" 不需要使用全限定类名。<cache />启用了基于namespace="net.aazj.mapper.UserMapper"的全局缓存。
5. generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration>
<classPathEntry location="D:\java_libs\repository\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar" /> <context id="MySQLTables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/sy"
userId="root"
password="xxxxx">
</jdbcConnection> <javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <javaModelGenerator targetPackage="net.aazj.pojo" targetProject="sp\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator> <sqlMapGenerator targetPackage="config.mappers" targetProject="sp\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="net.aazj.mapper" targetProject="sp\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <table schema="sy" tableName="tbug" domainObjectName="Bug" >
<property name="useActualColumnNames" value="false"/>
<generatedKey column="id" sqlStatement="mysql" identity="true" />
<!--
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
-->
</table>
<table schema="sy" tableName="user" domainObjectName="User" >
<property name="useActualColumnNames" value="false"/>
<generatedKey column="id" sqlStatement="mysql" identity="true" />
</table> </context>
</generatorConfiguration>
上面是Mybatis generator的配置文件:
1)classPathEntry 指定驱动位置;
2)jdbcConnection 指定数据库连接信息;
3)javaModelGenerator 指定生成的pojo类的位置;
4)sqlMapGenerator 指定指定生成的sql xml文件的位置;
5)javaClientGenerator 指定 mapper 接口的位置;
6)table 指定将数据库中哪些表进行处理;<generatedKey column="id" sqlStatement="mysql" identity="true" /> 用于指定主键;
6. 补上spring+mybatis多数据源的配置
其实很简单,就是需要将涉及到数据库,事物等相关的配置配置两份就行了,下面是修改之后的applicaitonContext.xml:
<?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: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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="net.aazj.service" />
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config/db.properties" /> <!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:config/mappers/**/*.xml" />
</bean> <!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" /> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="net.aazj.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean> <!-- ===============第二个数据源的配置=============== -->
<bean name="dataSource_slave" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url_slave}" />
<property name="username" value="${jdbc_username_slave}" />
<property name="password" value="${jdbc_password_slave}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
</bean> <bean id="sqlSessionFactory_slave" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource_slave" />
<property name="configLocation" value="classpath:config/mybatis-config-slave.xml" />
<property name="mapperLocations" value="classpath*:config/mappers/slave/**/*.xml" />
</bean> <!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager_slave" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource_slave" />
</bean> <!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager_slave" /> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="net.aazj.mapper.slave" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory_slave"/>
</bean>
</beans>
主要是注意在两个MapperScannerConfigurer中都通过sqlSessionFactoryBeanName指定了sqlSessionFactory。这样的话,在mapper接口中注入的就是不同的sqlSessionFactory,而不同的sqlSessionFactory又引用不同的dataSource和不同的configLocation,以及不同的mapperLocations。而MapperScannerConfigurer在扫描mapper接口所在的包路径时,会将其装配成bean。所以我们可以在serviceImpl中使用@Autowired等注解来引用:
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
// ... ...
}
SpringMVC4 + Spring + MyBatis3 基于注解的最简配置的更多相关文章
- 10 Spring框架--基于注解和xml的配置的应用案例
1.项目结构 2.基于xml配置的项目 <1>账户的业务层接口及其实现类 IAccountService.java package lucky.service; import lucky. ...
- SpringMVC4 + Spring + MyBatis3
SpringMVC4 + Spring + MyBatis3 本文使用最新版本(4.1.5)的springmvc+spring+mybatis,采用最间的配置方式来进行搭建. 1. web.xml 我 ...
- Spring:基于注解的Spring MVC
什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...
- Spring boot 基于注解方式配置datasource
Spring boot 基于注解方式配置datasource 编辑 Xml配置 我们先来回顾下,使用xml配置数据源. 步骤: 先加载数据库相关配置文件; 配置数据源; 配置sqlSessionF ...
- 基于注解的Dubbo服务配置
基于注解的Dubbo服务配置可以大大减少dubbo xml配置文件中的Service配置量,主要步骤如下: 一.服务提供方 1. Dubbo配置文件中增加Dubbo注解扫描 <!-- ...
- 分布式事务、多数据源、分库分表中间件之spring boot基于Atomikos+XADataSource分布式事务配置(100%纯动态)
本文描述spring boot基于Atomikos+DruidXADataSource分布式事务配置(100%纯动态),也就是增加.减少数据源只需要修改application.properties文件 ...
- Spring+Mybatis基于注解整合Redis
基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载 ...
- 【Spring】基于注解的实现SpringMVC+MySQL
目录结构: // contents structure [-] SprinigMVC是什么 SpringMVC工作原理 @Controller和@RequestMapping注解 @Controlle ...
- spring mvc 基于注解的使用总结
本文转自http://blog.csdn.net/lufeng20/article/details/7598801 概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Sprin ...
随机推荐
- HTML简明教程(一)
HTML简明教程(一) 内容主体来自:W3School 一.HTML 简介 二.HTML 基础 三.HTML 元素 四.HTML 属性 五.HTML 标题 六.HTML 段落 七.HTML 文本格式化 ...
- 0422 Step2-FCFS调度
一.目的和要求 1. 实验目的 (1)加深对作业调度算法的理解: (2)进行程序设计的训练. 2.实验要求 用高级语言编写一个或多个作业调度的模拟程序. 单道批处理系统的作业调度程序.作业一投入运行, ...
- 重构第7天 重命名(Rename )
理解:重命名就是把一些函数.字段.类.参数的名称 重命名为易于理解,最好是和自身的意义相同的名称.这样更易于理解,也可以减少大量的注释,名字即含义. 详解: 这个重构方法是我经常也是最常用的一种.我们 ...
- asp.net中绘制大数据量的可交互的图表
在一个asp.net项目中要用到能绘制大数据量信息的图表,并且是可交互的(放大.缩小.导出.打印.实时数据),能够绘制多种图形. 为此进行了多方调查预研工作,预研过微软的MsChart图表组件.基于j ...
- MIME(Multipurpose Internet Mail Extensions)的简介
多用途互联网邮件扩展类型(MIME) 作用:用于标识Web资源类型(Multipurpose Internet Mail Extensions,MIME) 效果:Web上MIME为每种类型的资源提供一 ...
- 设置窗体透明C#代码
上个示例是C#调用windows api 在原来代码上加入窗体透明,控件不透明代码: using System; using System.Runtime.InteropServices; using ...
- C# 生成BMP图片
;i<;i++) { Bitmap bmp=new Bitmap(this.pictureBox1.Image); Graphics g=Graphics.FromImage((Image)bm ...
- 用SQL语句修复SQL Server数据库
使用数据库的过程中,由于断电或其他原因,有可能导致数据库出现一些小错误,比如检索某些表特别慢,查询不到符合条件的数据等. 出现这些情况的原因,往往是因为数据库有些损坏,或索引不完整. 在ACCESS中 ...
- dapper的增、删、查改的CodeSmith模板
<%@ Template Language="C#" TargetLanguage="Text" %> <%@ Property Name=& ...
- html-制作导航菜单
导航菜单nav: 1.使用列表标签<ul> 2.使用浮动布局float 3.使用超链接标签<a>:要使用<a>标签的margin外边距,需要让<a>标签 ...