Developing a "Hello World" web App with spring boot

Source: Internet
Author: User

Environment preparation

Since many Ides now support MAVEN, we will use MAVEN to build the project;

Before you start, you'll need to install Java and maven:

This project will be based on the spring Boot 1.4.3.RELEASE Development, the recommended Java version is the Java 7+,maven version is 3.2+, you can use the following command to check whether compliance requirements:

Create Pom

With Maven built, we first need to create a pom.xml file to build this project, open your favorite editor (like notepad++) and add the following:

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "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.example</groupId>    <Artifactid>MyProject</Artifactid>    <version>0.0.1-snapshot</version>    <Parent>        <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring-boot-starter-parent</Artifactid>        <version>1.4.3.RELEASE</version>    </Parent>    <!--Additional lines to being added here ... -</Project>
Add dependency

Spring Boot provides a series of "initiators" that make adding dependencies very simple;

Since this project is a Web project, we choose to add spring-boot-starter-web "initiator" dependency;

Add spring-boot-starter-web Dependency

    <Dependencies><dependency> Span style= "color: #0000ff;" ><groupid>org.springframework.boot</groupid> artifactid>spring-boot-starter-web</artifactid> dependency> dependencies>      

In order to see the dependency of the introduction more intuitively spring-boot-starter-web , we can use the MVN dependency:tree command to view the project's dependency tree, and the following is the difference between the additions:

Before (observe, although inherit the Spring-boot-starter-parent, but did not introduce any dependency):

After:

It can be found that the dependencies of spring-boot-starter-web Tomcat, Jackson, and Spring boot are added automatically before the project is added and dependencies are added.

Finally, it is worth noting that, for the sake of simplicity, our project is inherited Spring-boot-starter-parent project, spring-boot-starter-parent help us to pre-define a lot of plug-in management configuration, compile level (Java 6) , encoding (UTF-8), etc., but did not add any dependencies, interested can view the spring-boot-starter-parent works of pom.xml files, links are as follows:

Https://github.com/spring-projects/spring-boot/blob/master/spring-boot-starters/spring-boot-starter-parent/pom.xml

Writing code

In order to complete this application, we need to create a simple Java file, as follows, MAVEN will go to the directory to compile the Java file by default, src/main/java so we need to create this directory structure and then add the src/main/java/Example.java file:

Importorg.springframework.boot.*;ImportOrg.springframework.boot.autoconfigure.*;ImportOrg.springframework.stereotype.*;Importorg.springframework.web.bind.annotation.*; @RestController @enableautoconfiguration Public classExample {@RequestMapping ("/") String Home () {return"Hello world!"; }     Public Static voidMain (string[] args)throwsException {springapplication.run (Example.class, args); }}

Observe the above code, we use the@RestController和@RequestMapping两个Spring MVC的注解,

@RestController用于表明该类是一个Controller,且返回的内容直接写入到响应body里;

@RequestMappingFor URL route mapping, where the surface path is "/" the HTTP request will be mapped to home () this method to handle;

In addition, with @EnableAutoConfiguration annotations added, spring boot automatically configures spring based on the dependencies you add, and because of the spring-boot-starter-web addition of Tomcat and Spring MVC, spring Boot Autoconfiguration assumes that you are developing a Web application and automatically adds the relevant spring configuration accordingly.

Finally, to focus on is the main method, and the normal main method is no different, only a word, call the Springapplication Run method to launch the application.

Run the app with the MAVEN command

Since the spring-boot-starter-parent project is inherited, we can use the mvn spring-boot:run command directly来运行程序,如下所示:

$ MVN spring-Boot:run. ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ |'_ | '_| |'_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/: : Spring Boot:: (v1.4.3. RELEASE) ........ ....... (log output here) ........ ..... Started Exampleinch 2.222Seconds (JVM running for 6.514)

After booting, you can see the results returned by the home method in the controller in the browser input http://localhost:8080/:

Alternatively, ctrl-c, you can close the app.

Create an executable jar package

Very simple, add a Maven plugin, the following code;

<Build><Plugins><Plugin> <groupid>org.springframework.boot</groupid> <artifactid</artifactid> </plugin> </plugins>< Span style= "color: #0000ff;" ></build>       

Then run mvn package the command (note, spring-boot-starter-parent的POM已经帮我们做了配置,绑定了repackage goal, 如果没使用继承parent POM,我们需要做更多配置,详情参考plugin documentation ):

After the package is finished, we can find the Helloworld-0.0.1-snapshot.jar package in the target directory.

If you want to run the program, it is also very simple, enter the Java-jar target/helloworld-0.0.1-snapshot.jar command to launch the application, as follows:

$ Java-jar target/helloworld-0.0.1-snapshot.jar  .   ____ _ _ _ _/\\/___ _ _ _ _            (_) _ __  _ \ \ \ (() \___ | ' _ | ' _| | ' _ \ _ ' | \ \ \  \\/  ___)| |_)| | | | | || (_| |  ) ))  '  |____|. __|_| |_|_| |_\__, |////=========|_|==============|___/=/_/_/_/:: Spring Boot::  (v1. 4.3.RELEASE) ........ ....... (log output here) ........ ..... Started Example in 2.536 seconds (JVM running for 2.864)

Similarly, after booting, you can see the results returned by the home method in the controller when the browser enters http://localhost:8080/.

IDE recommendations

Finally, although this example does not use any Ides, it is mainly because it is relatively simple, and if you are developing complex applications, it is strongly recommended to use the IDE, such as spring Tool Suite, which I am using the sts-3.8.3.release version.

Resources

http://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/

Developing a "Hello World" web App with spring boot

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.