本文使用最新版本(4.1.5)的springmvc+spring+mybatis,采用最間的配置方式來(lái)進(jìn)行搭建。
1. web.xml
我們知道springmvc是基于Servlet: DispatcherServlet來(lái)處理分發(fā)請(qǐng)求的,所以我們需要先在web.xml文件中配置DispatcherServlet,而Spring的啟動(dòng)則是使用了監(jiān)聽器,所以需要配置spring的監(jiān)聽器:
<?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相關(guān)的都在該文件中進(jìn)行配置。在DispatcherServlet(其父類)中使用:getServletConfig().getInitParameter("paramName"); 可以訪問(wèn)到init-param中指定的參數(shù),從而可以讀取到config/spring-mvc.xml文件。load-on-startup值為1指定了dispatcherServlet隨servlet容器啟動(dòng)。
ContextLoaderListener是spring監(jiān)聽servlet容器的啟動(dòng)的,在servlet容器啟動(dòng)時(shí),就初始化bean工廠,對(duì)bean進(jìn)行初始化等等操作。context-param指定了spring的配置文件config/applicationContext.xml,可以使用:getServletContext().getInitParameter("paraName"); 讀取到值。
注意:init-param 和 context-param 的區(qū)別,從名字上就可以看得出,后者是相對(duì)于整個(gè)web應(yīng)用的,而前者是針對(duì)單個(gè)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>
啟用注解驅(qū)動(dòng)來(lái)掃描controller,并指定control的包路徑,還有指定了視圖解析器,so easy。
注:這里要特別注意,springmvc和spring的配置文件中都有context:component-scan,一個(gè)是掃描controller,一個(gè)時(shí)掃描service,在指定掃描路徑時(shí)最好不要一樣,不要讓他們交叉掃描,不然會(huì)導(dǎo)致事務(wù)不能回滾的錯(cuò)誤。如果一定要一樣的話那么可以使用如下配置來(lái)進(jìn)行排除:
<!-- 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中相關(guān)bean掃描,事物的配置,以及和mybatis的結(jié)合配置如下所示:
<?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" /> <!-- 配置數(shù)據(jù)源 --> <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" /> <!-- 連接池最大使用連接數(shù)量 --> <property name="maxActive" value="20" /> <!-- 連接池最大空閑 --> <property name="maxIdle" value="20" /> <!-- 連接池最小空閑 --> <property name="minIdle" value="0" /> <!-- 獲取連接最大等待時(shí)間 --> <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定義事務(wù) --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="net.aazj.mapper" /> </bean></beans>
同樣相關(guān)service bean也使用基于注解的掃描方式:context:component-scan,事務(wù)也使用注解來(lái)驅(qū)動(dòng):tx:annotation-driven,所以需要在serviceImpl相關(guān)類上和方法上使用@Transanctional注解類配置事物。
sqlSessionFactory的配置相當(dāng)重要,configLocation指定了mybatis的配置文件,如果需要在mybatis配置文件中配置比如<settings>, <typeAliases>, <mappers>則,需要在這里指定,如果不需要就沒(méi)有必要指定值了。mapperLocations指定了mapper接口映射sql語(yǔ)句的xml文件的位置。MapperScannerConfigurer指定了mapper接口所在的包路徑。
4. mybatis-config.xml
spring和mybatis的接口,其實(shí)可以不需要mybatis-config.xml文件的存在,只有在需要配置<settings>, <typeAliases>, <mappers>(其實(shí)mapper也一并也是在applicationContext.xml中進(jìn)行配置)才需要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="mult<settings>指定了數(shù)據(jù)庫(kù)操作相關(guān)的設(shè)置,typeAliases指定了可以給數(shù)據(jù)庫(kù)表對(duì)應(yīng)的類所在的包路徑,可以在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 來(lái)代替: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 指定驅(qū)動(dòng)位置;
2)jdbcConnection 指定數(shù)據(jù)庫(kù)連接信息;
3)javaModelGenerator 指定生成的pojo類的位置;
4)sqlMapGenerator 指定指定生成的sql xml文件的位置;
5)javaClientGenerator 指定 mapper 接口的位置;
6)table 指定將數(shù)據(jù)庫(kù)中哪些表進(jìn)行處理;<generatedKey column="id" sqlStatement="mysql" identity="true" /> 用于指定主鍵;
6. 補(bǔ)上spring+mybatis多數(shù)據(jù)源的配置
其實(shí)很簡(jiǎn)單,就是需要將涉及到數(shù)據(jù)庫(kù),事物等相關(guān)的配置配置兩份就行了,下面是修改之后的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" /> <!-- 配置數(shù)據(jù)源 --> <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" /> <!-- 連接池最大使用連接數(shù)量 --> <property name="maxActive" value="20" /> <!-- 連接池最大空閑 --> <property name="maxIdle" value="20" /> <!-- 連接池最小空閑 --> <property name="minIdle" value="0" /> <!-- 獲取連接最大等待時(shí)間 --> <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定義事務(wù) --> <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> <!-- ===============第二個(gè)數(shù)據(jù)源的配置=============== --> <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" /> <!-- 連接池最大使用連接數(shù)量 --> <property name="maxActive" value="20" /> <!-- 連接池最大空閑 --> <property name="maxIdle" value="20" /> <!-- 連接池最小空閑 --> <property name="minIdle" value="0" /> <!-- 獲取連接最大等待時(shí)間 --> <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定義事務(wù) --> <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>主要是注意在兩個(gè)MapperScannerConfigurer中都通過(guò)sqlSessionFactoryBeanName指定了sqlSessionFactory。這樣的話,在mapper接口中注入的就是不同的sqlSessionFactory,而不同的sqlSessionFactory又引用不同的dataSource和不同的configLocation,以及不同的mapperLocations。而MapperScannerConfigurer在掃描mapper接口所在的包路徑時(shí),會(huì)將其裝配成bean。所以我們可以在serviceImpl中使用@Autowired等注解來(lái)引用:
@Service("userService")@Transactionalpublic class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; // ... ...}
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注