Spring Boot integrated mybatis Development WEB Project __web

Source: Internet
Author: User
Tags java web server port
1. Maven constructs spring Boot

Create a MAVEN Web project that introduces spring-boot-starter-parent dependencies

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>xyz.ibenben</groupId> <artifactid>zhongdian</ artifactid> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> &LT;NAME&G T;zhongdian Maven webapp</name> <url>http://maven.apache.org</url> <!--Inherit defaults fro M Spring Boot--> <parent> <groupId>org.springframework.boot</groupId> <artifa Ctid>spring-boot-starter-parent</artifactid> <version>1.4.0.BUILD-SNAPSHOT</version> < /parent> <!--Add Typical dependencies for a Web application--> <dependencies> <depend Ency> <groupid>org.spriNgframework.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> &LT;/DEP Endency> </dependencies> <!--Package as an executable jar--> <build> <plu
                Gins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> & lt;/build> <!--Add Spring repositories--> <!--(you don ' t need this if you are using a. Release version)--> <repositories> <repository> <id>spring-snapshots</id&
            Gt <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true&lt ;/enabled> </snapshots> </repository> <repository> <id> Spring-milestones</id> <url>http://repo.spring.io/milestone</url> </repository> </reposito 
            ries> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginrep Ository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</
 url> </pluginRepository> </pluginRepositories> </project>

Using Spring-boot-starter-parent to build a spring boot project is a great way to do it, but many of the projects themselves depend on other parent modules, Again, or spring-boot-starter-parent by default, there are so many configurations and features that we can't use.

We can also use other dependencies to introduce spring Boot.

<dependencyManagement>
     <dependencies>
        <dependency>
            <!--Import dependency Management from Spring Boot-->
            <groupId>org.springframework.boot</groupId>
            <artifactid >spring-boot-dependencies</artifactId>
            <version>1.4.0.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </ Dependencies>
</dependencyManagement>

This is the spring website to the demo configuration, interested in can jump over to see directly: http://docs.spring.io/spring-boot/docs/1.4.0.RC1/reference/htmlsingle/# Getting-started-maven-installation 2, the code structure of the Spring boot project

The Spring boot project does not differ much from the code structure of a typical Java Web project, but in order to reduce the number of configurations (no configuration), Spring boot has some good suggestions.

COM
 +-Example
     +-myproject
         +-application.java
         |
         +-Domain
         |   +-Customer.java
         |   +-Customerrepository.java
         |
         +-Service
         |   +-Customerservice.java
         |
         +-Web
             +-Customercontroller.java
2.1 Do not use the default package path

The classes we leave to spring management need to be placed under a package. The Defaultclass.java in the picture below are not possible. Because spring boot scans the annotated classes, the classes under these default package paths can be problematic.

Of course, based on the requirements of code specifications, the average programmer will not build their own code, it is explained that in order to really encounter this problem, you can quickly solve problems.

2.2 Spring boot application portal

Package com.example.myproject;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
Import Org.springframework.context.annotation.ComponentScan;
Import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan Public
class Application {public

    static void Main (string[] args) {
        springapplication.run (application.class, args);
    }

}

The entry class application with the main method, we can start the Spring boot project directly by running the main method, which greatly facilitates our debugging programs and programs.

Application class describes yourself as the entry class for spring boot, you need to add a @configuration annotation.

@EnableAutoConfiguration used to be on the Main method class application, when the project runs, the spring container automatically finds classes with specific annotations, such as @entity, @Service, and so on.

@ComponentScan If you do not take the Basepackage attribute, it automatically scans for classes under all child packages under the parent node for the package that contains the entry class. This is also what spring boot would suggest we put the application class under the root package path.

If our project is like the code structure proposed by spring boot, the application class is placed under the root package path. Then we can use @springbootapplication to replace the three annotations above.

Package com.example.myproject;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public
class Application {public

    static void Main (string[] args) {
        Springapplication.run (Application.class, args);
    }

3, the Spring Boot Web project implementation 3.1 Application class supports Web applications
@SpringBootApplication public
class application extends Springbootservletinitializer {

    @Override
    Protected Springapplicationbuilder Configure (Springapplicationbuilder application) {return
        Application.sources (Application.class);
    }

    public static void Main (string[] args) throws Exception {
        springapplication.run (application.class, args);

}

The entry class application inherits Springbootservletinitializer and overrides the Configure method. After you run the main method, we package our Web project as a war and start a Tomcat container with a port of 8080 to run our Web project by default. 3.2 Other server software support

If we do not want to use Tomcat, but other server software, such as jetty. You need to remove Tomcat dependencies and join jetty dependencies.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId> spring-boot-starter-web</artifactid>
    <exclusions>
        <exclusion>
            <groupId> Org.springframework.boot</groupid>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    < Groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-jetty</ Artifactid>
</dependency>
3.3 Server Port changes

Add application.yml configuration file.

# Server Settings  
server:  
    port:80
    address:127.0.0.1

Notice here that the YML configuration file is preceded by a space in the value attribute, and if there are no spaces, the spring parser ignores this configuration item. 3.4 Controller

Spring supports the way the controler of spring MVC is used.
Please refer to: http://blog.csdn.net/p_3er/article/category/2868979

The @restcontroller controller in the Spring boot application has the default Jackson2-based object-turn JSON feature. Such as:

@RestController public
class Mycontroller {

    @RequestMapping ("/thing") public
    mything Thing () {
            return new mything ();
    }

3.5 Configuration code and JSP support
# Spring PROFILES  
Spring:         
    # http ENCODING  
    http:  
        encoding.charset:utf-8  
        encoding.enable: True  
        encoding.force:true  
    MVC:
        view.prefix:/web-inf/jsp/
        view.suffix:. jsp

After adding the above configuration, you also need to introduce the Jasper package dependencies that are used to compile the JSP.

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId> tomcat-embed-jasper</artifactid>
            <scope>provided</scope>
        </dependency>

After adding JSP support configuration, the following a method and B method is to jump to the/web-inf/jsp/regiester.jsp page.

Package Xyz.letus.boot.controller;

Import Java.util.Map;

Import Javax.servlet.http.HttpServletRequest;

Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping ("/page") public
class Pagecontroller {

    @RequestMapping ("/a")
    public String B (map<string, object> model) {
        model.put ("msg", "John");     
        return "Regiester";
    }

    @RequestMapping ("/b") Public
    Modelandview B (httpservletrequest request) {
        Modelandview view = new Modelandview ();
        View.setviewname ("Regiester");

        Request.setattribute ("msg", "Davie");
        return view;
    }

3.6 Spring Boot Application for hot deployment

Adding springloaded dependencies to plug-in management is OK.

<!--Package as an executable jar-->
    <build>
        <plugins>
            <plugin>
                <groupid >org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                <!--Spring Thermal deployment-->
                <dependency>
                    <groupId> org.springframework</groupid>
                    <artifactId>springloaded</artifactId>
                </dependency >
            </dependencies>
            </plugin>
        </plugins>
    </build>

When the system is started by MVN spring-boot:run or right button application Debug startup Java file, the system will monitor classes files, when classes files are changed, the system will reload the class file, do not restart the service.

Note: Using application run (not in debug mode), the thermal deployment function will fail. 4. Spring Boot Integration MyBatis 4.1 Adding base dependencies

MyBatis:

<!--https://mvnrepository.com/artifact/org.mybatis/mybatis-->
        <dependency>
            <groupId> org.mybatis</groupid>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</ Version>
        </dependency>

Mybatis-spring-boot-starter:

<!--https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter-->
        < dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId> mybatis-spring-boot-starter</artifactid>
            <version>1.1.1</version>
        </dependency >

Mysql:

<!--Https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
        <dependency>
            < groupid>mysql</groupid>
            <artifactId>mysql-connector-java</artifactId>
        </ Dependency>
4.2 Database Configuration
# Spring PROFILES  
Spring:         
    # DATASOURCE  
    DATASOURCE:  
        driverClass:com.mysql.jdbc.Driver  
        URL:JDBC : Mysql://127.0.0.1:3306/hire?useunicode=true&characterencoding=utf-8  
        username:root  
        password:test  
4.3 introduction of General mapperIntroducing Dependency
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactid>mapper</artifactid >
            <version>3.3.7</version>
        </dependency>
Configure Generic Mapper
Package xyz.ibenben.zhongdian.common.configure;
Import Org.springframework.boot.autoconfigure.AutoConfigureAfter;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

Import Tk.mybatis.spring.mapper.MapperScannerConfigurer;


Import java.util.Properties; @Configuration public class Mybatismapperscannerconfig {@Bean public mapperscannerconfigurer mapperscannerconfig
        Urer () {mapperscannerconfigurer mapperscannerconfigurer = new Mapperscannerconfigurer ();
        Mapperscannerconfigurer.setsqlsessionfactorybeanname ("Sqlsessionfactory");
        Mapperscannerconfigurer.setbasepackage ("Xyz.ibenben.zhongdian.*.dao");
        Properties Properties = new properties ();
        Properties.setproperty ("Mappers", "Xyz.ibenben.zhongdian.common.BaseDao");
        Properties.setproperty ("Notempty", "false");
        Properties.setproperty ("IDENTITY", "MYSQL");
   Mapperscannerconfigurer.setproperties (properties);     return mapperscannerconfigurer;
 }

}

In fact Mybatismapperscannerconfig is a MYBATIS Scan mapper interface scan.

Mapperscannerconfigurer creates a mapper based on the specified creation interface or annotation. Here we map the interfaces under the Xyz.ibenben.zhongdian.*.dao package.

Using Mapperscannerconfigurer, there is no need to specify Sqlsessionfactory or Sqlsessiontemplate, Because Mapperscannerconfigurer will create Mapperfactorybean and then assemble automatically. However, if you use more than one datasource (and therefore also multiple sqlsessionfactory), then automatic assembly may fail. In this case, you can use the Sqlsessionfactory or Sqlsessiontemplate property to set the correct factory/template.

Note that some articles on the network have been configured with Mybatisconfig before Mapperscannerconfigurer, because Mapperscannerconfigurer will create Mapperfactorybean, So I don't have to configure mybatisconfig in my project. There is no problem with the use. 4.4 Use of universal Mapper (DAO layer)

Basedao:

Package Xyz.ibenben.zhongdi

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.