Spring-boot Quick Build Web Project Detailed summary

Source: Internet
Author: User

Recently in learning Spring boot-related technology, just touch on a kind of brief encounter feeling, because the project is built with spring boot is too convenient, we often only need a few simple steps, we can complete a spring MVC project to build, feel is:

OK, the following is the process of building my project simply say how to quickly build a spring MVC project, believe me, spring-boot this train, you on the basic can not stop!

Here is the main content of this blog:

1. Spring Boot Introduction

2. Quick build of Spring boot project

3. Unit Test in Spring-boot

4. Spring Boot and MyBatis integration

First, the initial knowledge of spring boot

  1, the traditional way to build Web projects

Import the jar package, configure Tomcat's Context.xml, Web. XML, configure class path, start. How can I get a bunch of errors? ClassNotFoundException? The elder brother does not import the jar package, oh version is wrong, then I use MAVEN management jar package, painstakingly finally configured Maven and learned how to use, start also did not error, but have been playing for a long time I have not started the formal code of writing, hurriedly began to write business code it, Also found that the spring configuration is always a bug, and I just want to get a simple e-mail function ah.

So, to build a Web project, many of the steps are repetitive, what tools can be achieved in one step? I just want to quickly put into the actual business development, I do not want to toss the jar version of the problem, no longer want to toss that tedious configuration process (although this is a good learning process), then, Spring boot estimate is the old iron you do not two of the choice!

  2. What is Spring boot?

What is Spring boot? Introduction to the direct copy website:

Forgive me the English, the official website said, Spring boot can let you in a very simple way to build an opportunity application Spring project, and you ask to do just run this project, Spring boot integrates the mainstream framework, We build the project in about two or three minutes, and the Spring boot project requires very little configuration.

With spring boot, you'll find out what configuration issues, what jar pack problems are gone, and your productivity will improve a lot, because spring boot has helped you get a project prototype, you just need to add your own business code to this prototype, your service And DAO will be all right!

Is spring boot really that bad? OK, let's get to the bottom and talk about how to build a project using spring boot.

2. Quick build of Spring boot project

  1. Quickly build a spring MVC project

  Let's start with Hello World, follow my steps below and quickly build an MVC project with spring boot

The first step, the official officer net, the project original jar package selection, website online building address is as follows: https://start.spring.io/, look at the picture:

Special Note: In the selection of the jar package you want, generally includes three parts: The Web Part-contains the spring, springboot and other common web development must jar package, Spring provides the tool class part (Devtool), this for the thermal deployment effect; Spring boot automatically helps you inherit various database frameworks, and here I take mybatis as a demonstration example, and finally the jar package has the following effects:

The second step, download the project and import the IDE, of course, need the support of the version management tool, here is recommended IntelliJ idea development tool (it is simply the standard of web development!) ), specifically see below:

  

Unzip to get the project file, then, you can open our IDE, here is my favorite IntelliJ idea for example

Open idea, find the path to the File-->open--> selection project, find the Pom file and open it in project form

What does the third, Hello Spring project look like? After you open the project, MAVEN loads the necessary jar packages, and during this time you can go for a drink of longjing tea or coffee, and when the project is built, you will see a typical MAVEN directory structure like this:

What to put in the specific directory, please refer to, here is to add that Hellospringbootapplication is the entire project entrance, we start the project is no longer to start Tomcat, but run this class, The main method of this class is that the main method of the entire project is to execute the portal,

Fourth step, write Hello demo. Create a new package demo, and then create a new class Hellospringboot, writing the following code

@RestController  Public class hellospringboot {    = {"/hellospringboot"})    public  String hellospring () {        System.out.println ("Hello Spring Boot");         return "Hello Spring boot";    }}

We will not explain the contents of this class, first configure and start the site, initially feel the magic of Spring boot:

Before starting the Web site, because spring boot is the default automatic registration of loading database related class files, so in order not to error, We need to open the database and add the database configuration related files in the resource directory Application.property, here is the example of MySQL, the configuration file is as follows:

  

Spring.datasource.url=jdbc:mysql://localhost:3306/wenda?useunicode=true&characterencoding= Utf8&usessl=falsespring.datasource.username=rootspring.datasource.password=root

The meaning of each field in the configuration file the reader is also able to understand, which will be explained in detail later.

Of course, if the database is not installed, readers can also use the Exclude property declaration in the Hellospringbootapplication class to not automatically register the loading of database-related files, refer to the following code:

@SpringBootApplication (exclude={datasourceautoconfiguration.  Class, Mybatisautoconfiguration. class}) // the mybatisautoconfiguration.class here corresponds to your database framework  Public class hellospringbootapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (hellospringbootapplication. class , args);}    }

Then, all of our work is done, we can start the website, the time to witness the miracle.

Find the Hellospringbootapplication class, double hit the card, right-click the mouse, run, and the project starts.

After you start the Web site, enter Http://localhost:8080/helloSpringBoot to access the corresponding method. Browser and idea background effects

  

Here's a simple explanation of what this class means:

The first is the @restcontroller note: The big guy with the spring knows what it is, and when our other classes are referencing the class through spring, the first step is to register the class with spring, @ Restcontroller is equivalent to registering this class to the spring container of course, there is a more commonly used is the @controller, specifically they two differences after the discussion.

Then @requestmapping, by setting the Path property of the polygon inside the annotation, you can declare the access path relative to the project root path (localhost:8080).

  

 2. Using SPRINGMVC to implement the parameters in Spring boot project

The above demo method is just a very simple example, in the actual production, our application can not be so simple, the front end also need to transfer parameters to the background, so, with the spring Boot construction project, how to implement the parameter? (Feel the following is in summary sprign MVC related content, so the big God do not spray me out of the theme, because it feels like spring boot if it is summed up, it seems that there is no good summary, and spring boot is inherently impossible and other spring Component segmentation) Specifically, please open the following code example:

@RestController Public classHellospringboot {/*** URL parameter, access to the path similar to: LOCALHOST:8080/GETPARAMDEMO1/1 * method Body parameters in the previous annotated, @PathVariable, representing the parameters in the URL*/@RequestMapping (Path= {"/getparamdemo1/{id}"})     PublicString GetParamDemo1 (@PathVariable ("id")intuserId) {System.out.println ("Get Param" +userId); return"Success get Param"; }    /*** Of course, you can also pass this way: localhost:8080/getparamdemo?param1=1 or direct form submit parameters * Of course, the parameter declaration in the method of the annotation will also become @requestparam, representing the request parameters, re The Quired property describes whether the parameter is required*/@RequestMapping (Path= {"/getparamdemo2"})     PublicString GetParamDemo2 (@RequestParam (value= "param1", required =false)intparam) {System.out.println ("Get Param" +param); return"Success get Param"; }}

  

 3. Building a restful programming style

Recently, resultful style programming is quite fire (although the individual feels not to blindly follow suit), and spring boot in the use of its built-in spring MVC framework, can be very simple to implement this style of programming.

For example, I want to request a query for a data, in the programming style of the Resultful class, the query corresponds to a GET request, then spring boot (the exact spring MVC) can be processed for different requests, see the following code:

@RestController Public classHellospringboot {/*** By setting the method property of the requestmapping, you can set the corresponding request that can be processed by the methods, such as the following Getrequestdemo method will only handle get requests*/@RequestMapping (Path= {"/getrequestdemo"},method =requestmethod.get) PublicString Getrequestdemo (@RequestParam (value= "param1", required =false)intparam) {System.out.println ("Get request test, get Param" +param); return"Success get Param"; }    /*** The following Deleterequestdemo method will only process the delete request*/@RequestMapping (Path= {"/deleterequestdemo"},method =requestmethod.delete) PublicString Deleterequestdemo (@RequestParam (value= "param1", required =false)intparam) {System.out.println ("Delete request test, get Param" +param); return"Success get Param"; }}

In addition, the use of the above-mentioned URL value (similar to this: Path= "/member/{userid}") for resource positioning, but also very consistent with resultful style requirements, such as this Path= "/getparamdemo1/{userid}" Configuration is the corresponding to a member level of a user (located by userid) to do some action, if you want to delete the user, the corresponding HTTP request delete request.

With those steps above, it's clear how the reader can quickly build a simple Web project with spring boot, and how to do unit testing in the Spring boot build project.

Iii. unit testing issues in the Spring boot project

Spring Boot integrates the Junite framework, for unit testing, and not to write all kinds of tedious classes, only need to make certain comments on the test class, Spring boot will help you do everything, even if the database-related operations, spring boot can also be very good to test, In the case of the code example, here is an example of a simple test business class method:

First, we create a new service layer, add a demo class, and the final demo code is as follows:

@Component  Public class Servicedemo {    public  String Testdemo () {        = "I am returning results";         // here is the business code        return rtnafterdosomething;}    }

The following code is the test class

@RunWith (Springrunner.  Class) @SpringBootTestpublicclass  servicedemotest {    @Autowired    Servicedemo Servicedemo;    @Test    publicvoid  Testdemo () {        = Servicedemo.testdemo ();        " I am returning the result ");}    }

If you are testing a database DAO, it is similar, but it is important to note that the project must be started before testing (that is, the Hellospringbootapplication run method must be running)or the can not find will be wrapped. ApplicationContext's error.

Iv. Configuring the database framework in spring boot (with MyBatis as an example)

It is also convenient to integrate a database-related open source framework in spring boot (of course, remember to refer to the relevant JAR package when you start a new project), and when you have no errors on the steps above, You simply need to configure the next applocation.properties file to

Spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useunicode=true&characterEncoding= UTF8&usessl=falsespring.datasource.username=rootspring.datasource.password=root# The following configuration declares the configuration file path for MyBatis, and classpath corresponds to this file resourcesmybatis.config-location=classpath:mybatis-config.xml 

The file structure of the directory is referenced below:

Ok,mybatis The reference configuration is ready, below we try to use MyBatis This database framework, a simple query operation of the database, first, Look at the following Mybatis-config.xml configuration content, the reader can use this as a template configuration, of course, want to know more specific mybatis configuration instructions, recommend to visit the official website, here does not expand:

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Configuration Public "-//mybatis.org//dtd Config 3.0//en" "http://mybatis.org/dtd/mybatis-3-conf Ig.dtd "><Configuration>    <Settings>        <!--globally enables or disables any caches configured in any mapper under this configuration -        <settingname= "cacheenabled"value= "true"/>        <!--Sets the number of seconds the driver would wait for a response from the database -        <settingname= "Defaultstatementtimeout"value= " the"/>        <!--enables automatic mapping from classic database column names a_column to camel case Classic Java property names Acolu MN -        <settingname= "Mapunderscoretocamelcase"value= "true"/>        <!--allows JDBC support for generated keys.        A compatible driver is required. This setting forces generated keys to being used if set to true, as some drivers deny compatibility but still WOR K -        <settingname= "Usegeneratedkeys"value= "true"/>    </Settings>    <!--Continue going here -</Configuration>

Well, then, you can do the database operation, I simply used MySQL built a name for the Springboot database, in the library built a simple demo table (How to build the table that I do not have to say it? Really did not contact the database of students, you can Baidu or Google to go to it, then, the DAO code is as follows:

@Mapper  Public Interface Demodao {    @Select ({"select Demo_param from  demo"})    String Querydemo ();}

Note that MyBatis DAO is an interface, more content on MyBatis, please open the Official document, this is not expanded here.

Then, just call it in the original Servicedemo class, and look at the code:

  

Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Component;ImportOrg.springframework.stereotype.Controller;ImportSpringboot.hello.helloSpringboot.dao.DemoDao;@Component Public classServicedemo {@Autowired Demodao Demodao;  Publicstring Testdemo () {string rtnafterdosomething= "I am the return result"; //here is the business code        returnrtnafterdosomething; }     PublicString Querydemo () {returnDemodao.querydemo (); }}

OK, simply write a test class, there is a small green bar, test success.

Then, all the project prototypes are done, and then we can do our core business development, and soon there is no? Nice wood, huh? So, spring boot build project is really fast, can let us save a lot of mechanical pre-operation, readers hurriedly to explore the next, spring boot, you deserve to poke!

OK, today summarized here, this project code on GitHub on this address, need someone to pick up: https://github.com/lcpandcode/helloSpringboot.git

Say it again, spring boot, it's a damn good use! Come on, hurry up!

Spring-boot Quick Build Web Project Detailed summary

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.