Spring Boot 2.0.0 Reference Manual-Chinese version _part ii_11-12

Source: Internet
Author: User
Tags manual documentation http request xmlns tomcat

Article Author: Tyan
Blog: noahsnail.com |  CSDN | Jane Book 11. Develop your first spring boot app

We use Java to develop a simple Web application "Hello world!" that emphasizes some of the key features of spring boot through the application. Since most Ides support MAVEN, we use MAVEN to build this project.

There are many "Getting Started" guides on the Spring.io website that use spring boot. If you want to solve a particular problem, go to the website first.

You can simplify the following steps by going to Start.spring.io and selecting the Web Launcher from the dependent Finder. This will automatically generate a new engineering structure so you can start coding in the right way. See the documentation for more details.

$ java-version
java Version "1.7.0_51"
Java (tm) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot (tm ) 64-bit Server VM (build 24.51-b03, Mixed mode)
$ mvn-v
Apache maven 3.2.3 (33F8C3E1027C3DDDE99D3CDEBAD2656A31E8FDF4; 2014-08-11t13:58:10-07:00)
maven Home: /users/user/tools/apache-maven-3.1.1
Java version:1.7.0_51, vendor:oracle Corporation

This example needs to create its own folder. The next introduction assumes that you have created the appropriate folder and that the folder is your current directory. 11.1 Creating a Pom file

We first need to create a maven pom.xml file. Pom.xml is the prescription used to build the project. Open your favorite text editor and add the following:

<?xml version= "1.0" encoding= "UTF-8"?> <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/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.exam

    Ple</groupid> <artifactId>myproject</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot- starter-parent</artifactid> <version>2.0.0.BUILD-SNAPSHOT</version> </parent> &lt ;! --Additional lines to being added here ...-<!--(you don't need this if you're using a. RELEASE version)-<repositories> <repository> <id>spring-snapshots</id&
            Gt
 <url>http://repo.spring.io/snapshot</url>           <snapshots><enabled>true</enabled></snapshots> </repository> < Repository> <id>spring-milestones</id> &LT;URL&GT;HTTP://REPO.SPRING.IO/MILESTONE&L t;/url> </repository> </repositories> <pluginRepositories> <pluginreposito 
        Ry> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url>
            </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginrepositor Ies> </project>
11.2 Adding classpath dependencies

Spring Boot provides a number of "starters", which can be used to add jar packages to classpath in a container. Our example program has already used spring-boot-starter-parent in the parent part of the Pom. Spring-boot-starter-parent is a special launcher that provides useful MAVEN default settings. It also provides a dependency management section, so you can ignore its version label for "Blessed" dependencies.

When developing a particular application, the other "starters" simply provides the dependencies you may need. Since we are developing a Web application, we will add spring-boot-starter-web dependencies-but before that, let's take a look at what's going on.

$ mvn dependency:tree

[INFO] Com.example:myproject:jar:0.0.1-snapshot
11.3 Write Code

In order to complete our application, we need to create a simple Java file. The default MAVEN will compile the source code from Src/main/java, so you need to create a file structure and then add a file named Src/main/java/example.java:

Import org.springframework.boot.*;
Import org.springframework.boot.autoconfigure.*;
Import org.springframework.stereotype.*;
Import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration Public
class Example {

    @RequestMapping ("/")
    String Home () {
        return "Hello world!";
    }

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

}

Although there is not much code here, many are in progress. Let's step through these important parts. 11.3.1 @RestController and @requestmapping annotations

The first annotation in the example class is @restcontroller. This is a modal annotation. It gives hints to people reading the Code, and for spring, this class has a specific task. In this example, our class is a Web @Controller that spring will consider to handle when a Web request arrives.

@RequestMapping annotations Provide "routing" information. It tells Spring that any HTTP request with the path "/" should be mapped to the home method. @RestController annotation tells spring to render the result in a string form and return it directly to the caller.

@RestController and @requestmapping are spring MVC annotations (they are not spring-boot-specific). See the MVC section of the Spring reference documentation for more details. 11.3.2 @EnableAutoConfiguration Annotations

The second class-level annotation is @enableautoconfiguration. This note tells spring boot to "guess" how you want to configure spring based on the jar dependencies you add. Since Spring-boot-starter-web adds Tomcat and spring MVC, auto-configuration assumes that you are developing a Web application and setting up spring accordingly.

Initiator and automation configuration

Automatic configuration is designed to work well with the launcher, but these two concepts are not directly linked. You are free to pick a jar dependency outside of the launcher, and Spring boot will still maximize your app's automatic configuration. 11.3.3 The "main" method

The final part of the program is the main method. This is a standard approach that conforms to the Java Application Portal specification. The Springapplication class of the main method that delegates Spring boot calls the Run method. Springapplication will boot our app launch spring,spring will launch the automatically configured Tomcat Web server. We need to pass Example.class as a parameter to the Run method, telling Springapplication that it is the main spring component. The args array passes all command-line arguments to the Run method. 11.4 Run this example

At this point our application should work. Now that we have used the spring-boot-starter-parent POM, we have a useful run target that we use to launch the application. Enter MVN Spring-boot:run in the project's root directory to launch the app.

$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ))
  '  |____|. __|_| |_|_| |_\__, |////
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot::  (v2.0.0.build-snapshot)
..... ....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)

If you open a Web browser and enter localhost:8080, you should see the output below.

Hello world!

You can exit the app by clicking Ctrl-c. 11.5 Creating an executable jar

End our example by creating a complete self-contained executable jar file that can be run in the product. Executable jars (sometimes called "fat jars") is an archive file that contains all the jar dependencies required for the compiled class and code to run.

executable jars and Java

Java does not provide any standard way to load nested jar files (for example, the jar file itself is contained within a jar). This can be a problem if you want to distribute a self-contained app.

To solve this problem, many developers use "Uber" jars. The Uber jar simply packs all of the jars's classes into a single archive file. The problem with this approach is that it's hard to see which library your app is using. It is also a problem if multiple jars use the same file name (different content).

Spring boot takes a different approach to dealing with this problem, allowing you to actually embed jars directly.

In order to create the executable jar, we need to add spring-boot-maven-plugin to Pom.xml. Insert the following below the dependencies section:

<build>
    <plugins>
        <plugin>
            <groupid>org.springframework.boot</groupid >
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins >
</build>

The Spring-boot-starter-parent Pom contains the <executions> configuration of the binding repackage target. If you do not use the parent pom, then you need to declare this configuration yourself. See the plugin documentation for more details.

Save your Pom.xml and run the MVN package from the command line:

$ MVN Package

[INFO] scanning for projects
... [INFO]
[INFO]------------------------------------------------------------------------
[INFO] Building MyProject 0.0.1-snapshot
[INFO]------------------------------------------------------------------------
[INFO] .... ..
[INFO]---maven-jar-plugin:2.4:jar (default-jar) @ myproject---
[info] Building jar:/users/developer/example/ Spring-boot-example/target/myproject-0.0.1-snapshot.jar
[INFO]
[INFO]---spring-boot-maven-plugin : 2.0.0.build-snapshot:repackage (default) @ MyProject---
[INFO]--------------------------------------------- ---------------------------
[INFO] BUILD SUCCESS
[INFO]----------------------------------------------- -------------------------

If you look at the directory target you should see Myproject-0.0.1-snapshot.jar. The file size should be about ten MB. If you want to see what's inside, you can use: Jar TVF

$ jar TVF Target/myproject-0.0.1-snapshot.jar

You should also be able to see a smaller file named Myproject-0.0.1-snapshot.jar.original in the target directory. This is the original jar file that Maven created before spring Boot repackage.

To run this app, use the Java-jar command:

$ Java-jar target/myproject-0.0.1-snapshot.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ))
  '  |____|. __|_| |_|_| |_\__, |////
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot::  (v2.0.0.build-snapshot)
..... ....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)

As before, exit the app by clicking Ctrl-c. 12. What to read Next

Hopefully this section provides you with some basic spring boot basics that will allow you to write your own app. If you're a task-oriented developer, you might want to jump to Spring.io and find some getting started guidelines to solve specific "how to do with Spring", and we also provide a how-to reference document for spring boot.

Spring Boot Repository also has some examples that you can run. Examples are independent of other code (you do not need to build other content when running or using an example).

In addition, logic next reads the third part, "Using Spring Boot". If you are really impatient, you also skip this section and read the features of spring boot directly.

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.