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 distributing the request based on the Dispatcherservlet, so first build the Dispatcherservlet in the Web. xml file, as well as the Spring listener:

<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "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>

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.

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/schema/beanshttp//www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/mvchttp//www.springframework.org/schema/mvc/spring-mvc.xsdhttp//Www.springframework.org/schema/contexthttp//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= "/"/&gt         ; <property name= "suffix" value= ". jsp"/> </bean>//... ...</beans>

Enables note-driven, specifies the package path for control, and also specifies a view resolver, so easy.

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/beanshttp//www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context.xsd "><context:component-scan base- Package= "Net.aazj.service"/> <!--Introducing Properties file--<context:property-placeholder location= "Classpath:config/db.prope Rties "/> <!--configuration data source-<bean name=" DataSource "class= "Com.alibaba.druid.pool.DruidDataSource" init-method= "Init" destroy-method= "close" > <property name= "url" val Ue= "${jdbc_url}"/> <property name= "username" value= "${jdbc_username}"/> <property name= "Passwo        Rd "value=" ${jdbc_password} "/> <!--Initialize connection size-<property name=" initialsize "value=" 0 "/>        <!--connection Pool maximum usage connections-<property name= "maxactive" value= "/> <!--connection Pool Max free-- <property name= "Maxidle" value= "/> <!--connection pool min Free--<property name=" Minidle "value=" 0 "/ > <!--get connection maximum wait time-<property name= "maxwait" value= "60000"/> </bean> <b Ean id= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "dataSource" ref= "DataSource"/> <proper Ty name= "configlocation" value= "Classpath:config/mybatis-config.xml"/> <property name= "mapperLocations" value = "Classpath*:config/mappers/**/*.xml"/> </bean> <!--Transaction Manager forA single JDBC DataSource---<bean id= "TransactionManager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name= "DataSource" ref= " DataSource "/> </bean> <!--defining transactions with annotation--<tx:annotation-driven transaction-manager= "TransactionManager"/> <beanclass= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basepackage" value= "Net.aazj.mapper"/ > </bean></beans>

The same related service beans also use annotation-based scanning: Context:component-scan, so you need to use @transanctional annotation classes 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= "lazyloadingenabled" value= "true "/> <setting name=" multipleresultsetsenabled "value=" true "/> <setting name=" Usecolumnlabel "value=" t Rue "/> <setting name=" Usegeneratedkeys "value=" false "/> <setting name=" Automappingbehavior "value=" P Artial "/> <setting name=" Defaultexecutortype "value=" simple "/> <setting name=" Defaultstatementtimeou T "value="/> <setting name= "saferowboundsenabled" value= "false"/> <setting name= "Mapunderscoretoc Amelcase "value=" false "/> <setting name=" Localcachescope "value=" SESSION "/> <setting name=" JdbcTypeF Ornull "value=" other "/> <setting name=" lazyloadtriggermethods "value=" equals,clone,hashcode,tostring "/> &L T;/settings> <typealiases&Gt < PackageName= "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; @Alias ("User")  Public class User {    private  Integer ID;     Private String name;         //  ... ... }

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 ">        * 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".

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.