SpringMVC4 + Spring + MyBatis3 annotation-based minimalist configuration

Source: Internet
Author: User

This article uses the latest version (4.1.5) of the Springmvc+spring+mybatis, using the most configurable way to build.

1. Web. xml

We know that SPRINGMVC is based on Servlet:dispatcherservlet to handle the distribution request, So we need to configure the Dispatcherservlet in the Web. xml file First, and spring starts with a listener, so we need to configure Spring's listener:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" XM Lns: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> &L T;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> & Lt;param-value>classpath:config/spring-mvc.xml</param-value> </init-param> </servlet> < Servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-patt ern> </servlet-mapping> <listener> <listener-class>orG.springframework.web.context.contextloaderlistener</listener-class> </listener> <context-param > <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationc Ontext.xml</param-value> </context-param> </web-app>

The configuration file for the SPRINGMVC Dispatcherservlet is specified in Init-param below the servlet: Config/spring-mvc.xml, all SPRINGMVC related are configured in the file.  Used in Dispatcherservlet (its parent Class): Getservletconfig (). Getinitparameter ("paramname"); You can access the parameters specified in Init-param so that you can read to the Config/spring-mvc.xml file. A Load-on-startup value of 1 specifies that the Dispatcherservlet is started with the servlet container.

Contextloaderlistener is the start of the spring Listener servlet container, which initializes the Bean factory, initializes the bean, and so on when the servlet container is started. CONTEXT-PARAM Specifies the spring configuration file Config/applicationcontext.xml, which can be used: Getservletcontext (). Getinitparameter ("ParaName") ; Read the value.

Note: The difference between Init-param and Context-param can be seen from the name, which is relative to the entire Web application, whereas the former is for a single servlet.

2. Springmvc.xml

Let's take a look at how Springmvc.xml should be configured:

<?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/sche Ma/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.SPRINGF Ramework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/"/> &lt ;p roperty name= "suffix" value= ". JSP"/&Gt </bean>//... ...</beans>

Enable the annotation driver to scan the controller, specify the package path to control, and specify the view resolver, so easy.

Note : It is important to note that there are context:component-scan in the SPRINGMVC and spring configuration files, one for the scan controller and one for the scan service, preferably not the same when you specify the scan path. do not let them cross-scan, or it will cause the transaction not to roll back the error . If you must be the same, you can use the following configuration to exclude:

< class with @service annotations is not scanned in the configuration file for!--Springmvc--    <context:component-scan base-package= "NET.AAZJ" >        <context:exclude-filter type= "Annotation" expression= "Org.springframework.stereotype.Service"/> </    Context:component-scan>

<!--spring configuration file does not scan the class with @controller annotations-  -    <context:component-scan base-package= "NET.AAZJ" >        <context:exclude-filter type= "annotation" expression= "Org.springframework.stereotype.Controller"/>     </context:component-scan>

3. Applicationcontext.xml

The related bean scans in spring, the configuration of things, and the combination of MyBatis are as follows:

<?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/SPR Ing-beans.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema/tx/spring-tx.xs D Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context . xsd "> <context:component-scan base-package=" Net.aazj.service "/> <!--Introducing Properties Files--<context:prop  Erty-placeholder location= "Classpath:config/db.properties"/> <!--configuration Data Source--<bean name= "DataSource" Class= "Com.alibaba.druid.pool.DruidDataSource" Init-method= "Init" destroy-method= "close" > <property name= "url" value= "${jdbc_url}"/> <propert        Y name= "username" value= "${jdbc_username}"/> <property name= "password" value= "${jdbc_password}"/> <!--Initialize connection size-<property name= "initialsize" value= "0"/> <!--connection Pool maximum usage connections-&L T;property name= "maxactive" value= "/> <!--connection Pool Max free--<property name=" Maxidle "value=" 20 "/        > <!--connection pool min Idle--<property name= "Minidle" value= "0"/> <!--get connection Max wait Time- <property name= "maxwait" value= "60000"/> </bean> <bean id= "sqlsessionfactory" class= "Org.myb Atis.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=" transact Ionmanager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </bean> <!--using annotation to define transactions--<tx:annotation-driven tra nsaction-manager= "TransactionManager"/> <bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer"      ; <property name= "Basepackage" value= "Net.aazj.mapper"/> </bean></beans>

The same related service bean also uses annotation-based scanning: Context:component-scan, transactions are also driven using annotations: Tx:annotation-driven, So you need to use the @transanctional annotation class on Serviceimpl related classes and methods to configure things.

Sqlsessionfactory configuration is very important, configlocation specifies the MyBatis configuration file, if necessary in the MyBatis configuration file configuration such as <settings>, <typealiases , <mappers>, it needs to be specified here, and it is not necessary to specify a value if it is not required. mapperlocations Specifies the location of the XML file where the Mapper interface maps the SQL statement. MAPPERSCANNERCONFIGURER Specifies the package path where the Mapper interface resides.

4. Mybatis-config.xml

Spring and MyBatis interface, in fact, can not need the presence of mybatis-config.xml files, only in the need to configure <settings>, <typealiases>, <mappers> ( In fact, Mapper is also in the Applicationcontext.xml to be configured in order to require the existence of mybatis-config.xml files:

<?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= "lazy Loadingenabled "value=" true "/> <setting name=" multipleresultsetsenabled "value=" true "/> <setting nam E= "Usecolumnlabel" value= "true"/> <setting name= "Usegeneratedkeys" value= "false"/> <setting name= "au Tomappingbehavior "value=" PARTIAL "/> <setting name=" Defaultexecutortype "value=" simple "/> <setting n Ame= "Defaultstatementtimeout" value= "/> <setting name=" saferowboundsenabled "value=" false "/> <set      Ting 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> Specifies the database operation related settings, typealiases specifies the package path that can be used for the class that corresponds to the database table, and can use their aliases in SQL XML:

Package Net.aazj.pojo;import Org.apache.ibatis.type.Alias; the @Alias ("User") public class User {    private Integer ID;    private String name;        // ... ...}

@Alias ("User") annotated the alias of the Pojo, so you can use the alias user in the XML file instead: 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>

This resulttype= "user" does not require the use of fully qualified class names. <cache/> Enabled the global cache based on 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" Connectionur L= "Jdbc:mysql://localhost:3306/sy" userid= "root" password= "xxxxx" > </jdbcConnection> <java typeresolver > <property name= "forcebigdecimals" value= "false"/> </javaTypeResolver> <javamo Delgenerator targetpackage= "Net.aazj.pojo" targetproject= "Sp\src\main\java" > <property name= " Enablesubpackages "value=" true "/> <property name=" trimstrings "value=" true "/> &LT;/JAVAMODELGENERATOR&G    T <sqlmapgenerAtor targetpackage= "Config.mappers" targetproject= "sp\src\main\resources" > <property name= "enableSubPackages "Value=" true "/> </sqlMapGenerator> <javaclientgenerator type=" Xmlmapper "targetpackage=" Net.aazj.mappe R "targetproject=" Sp\src\main\java "> <property name=" enablesubpackages "value=" true "/> </javaClientG enerator> <table schema= "sy" tablename= "Tbug" domainobjectname= "Bug" > <property name= "useActualColumn       Names "value=" false "/> <generatedkey column=" id "sqlstatement=" mysql "identity=" true "/> <!-- <columnoverride column= "Date_field" property= "StartDate"/> <ignorecolumn column= "FRED"/> <colum Noverride column= "Long_varchar_field" jdbctype= "VARCHAR"/>-</table> <table schema= "sy" tab Lename= "User" domainobjectname= "user" > <property name= "Useactualcolumnnames" value= "false"/> <gener Atedkey column= "id" sqlstatement= "MySQL" identity= "true"/> </table> </context></generatorConfiguration> 

Above is the configuration file for MyBatis generator:

1) classpathentry specified driving position;

2) jdbcconnection Specify database connection information;

3) javamodelgenerator Specifies the location of the generated Pojo class;

4) sqlmapgenerator Specifies the location of the generated SQL XML file;

5) Javaclientgenerator Specify the location of the Mapper interface;

6) table specifies which tables in the database are processed; <generatedkey column= "id" sqlstatement= "mysql" identity= "true"/> used to specify the primary key;

6. Complement the configuration of Spring+mybatis multiple data sources

In fact, it is very simple, it is necessary to involve the database, things and other related configuration configuration two copies on the line, the following is the modified 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/SPR Ing-beans.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema/tx/spring-tx.xs D Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context . xsd "> <context:component-scan base-package=" Net.aazj.service "/> <!--Introducing Properties Files--<context:prop  Erty-placeholder location= "Classpath:config/db.properties"/> <!--configuration Data Source--<bean name= "DataSource" Class= "Com.alibaba.druid.pool.DruidDataSource" Init-method= "Init" destroy-method= "close" > <property name= "url" value= "${jdbc_url}"/> <propert        Y name= "username" value= "${jdbc_username}"/> <property name= "password" value= "${jdbc_password}"/> <!--Initialize connection size-<property name= "initialsize" value= "0"/> <!--connection Pool maximum usage connections-&L T;property name= "maxactive" value= "/> <!--connection Pool Max free--<property name=" Maxidle "value=" 20 "/        > <!--connection pool min Idle--<property name= "Minidle" value= "0"/> <!--get connection Max wait Time- <property name= "maxwait" value= "60000"/> </bean> <bean id= "sqlsessionfactory" class= "Org.myb Atis.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=" transact Ionmanager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </bean> <!--using annotation to define transactions--<tx:annotation-driven tra nsaction-manager= "TransactionManager"/> <bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer"      ; <property name= "Basepackage" value= "Net.aazj.mapper"/> <property name= "Sqlsessionfactorybeanname" value= "s Qlsessionfactory "/> </bean> <!--=============== configuration of the second data source ===============--<bean name=" Da Tasource_slave "class=" Com.alibaba.druid.pool.DruidDataSource "init-method=" Init "destroy-method=" close "> <p Roperty name= "url" value= "${jdbc_url_slave}"/> <property name= "username" value= "${jdbc_username_slave}"/&gt        ; <property name="Password" value= "${jdbc_password_slave}"/> <!--Initialize connection size--<property name= "InitialSize" value = "0"/> <!--connection Pool maximum usage connection number-<property name= "maxactive" value= "/> <!--connection Pool Max idle --<property name= "Maxidle" value= "/> <!--connection pool min Free---<property name=" Minidle         "value=" 0 "/> <!--get connection maximum wait time-<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=" Transac Tionmanager_slave "class=" org.springframework. Jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" Datasource_slave "/> & lt;/bean> <!--using annotation to define transactions--<tx:annotation-driven transaction-manager= "TRANSACTIONMANAGER_SL Ave "/> <bean class=" Org.mybatis.spring.mapper.MapperScannerConfigurer "> <property name=" basepack Age "value=" Net.aazj.mapper.slave "/> <property name=" sqlsessionfactorybeanname "value=" Sqlsessionfactory_ Slave "/> </bean></beans>

The main note is that sqlsessionfactory is specified through Sqlsessionfactorybeanname in two mapperscannerconfigurer. In this case, the Mapper interface is injected with different sqlsessionfactory, and different sqlsessionfactory refer to different datasource and different configlocation, and the different mapperlocations. Mapperscannerconfigurer, while scanning the package path where the Mapper interface is located, assembles it into a bean. So we can use annotations like @autowired in Serviceimpl to refer to:

@Service ("UserService") @Transactionalpublic class Userserviceimpl implements userservice{    @Autowired    Private Usermapper Usermapper;        // ... ...}

SpringMVC4 + Spring + MyBatis3 annotation-based minimalist configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.