Spring Boot Learning Note 1 Start your web App in the first 3 minutes of---experience

Source: Internet
Author: User

Objective

The simple use of spring Boot as early as last year was shocked by its handy features. But that is also not in-depth research, as its application in the industry more and more widely, so decided to study deeply, will own learning experience in this record, this article mainly around the following points to explain:

    • About Spring Boot
    • Quickly build a web App with spring boot
      If there is something wrong, please correct me.
1. Introduction to Spring Boot

Spring Boot is a spring-based derivative framework whose main purpose is to help us quickly build an independent, production-level spring application that advocates a "contract better than a configuration" approach.
Its main features are as follows:

    1. Create a separate spring app
    2. Built-in web container (using Tomcat by default, if you want to switch to jetty simply by modifying the configuration), you can start the Web App in Java application.
    3. A large number of Maven template configurations are available (often referred to as starter POMs), and by using the MAVEN configuration it provides, it integrates the dependencies we use for daily development, thus greatly reducing the amount of work we can do with the configuration of Maven's pom files.
    4. The spring is automatically configured to infer your current operating environment based on the jar package under your current classpath path, helping us to create some objects that should be used, and start them in their own way, based on the corresponding environment.
    5. Provides some features in the production environment: such as indicator statistics, health checks.
    6. No redundant code and XML configuration is required.
    7. A ready-made MAVEN plugin is available that makes it easier to package with Maven.
2. Spring Boot Start experience

After a brief look at spring boot, let's quickly build a web App with spring boot to quickly feel the power of spring boot.

2.1 Quickly build a Web application

The introduction of MAVEN dependencies:

    <!--Use the official latest version, the official recommendation is to inherit the default Springboot configuration inheritance, the project's compilation level automatically becomes the jdk1.6 version. -<Parent><Groupid>org.springframework.boot</Groupid><Artifactid>spring-boot-starter-parent</Artifactid><version>1.3.3.release</version > </parent> <!-- Add a dependency on a web app that automatically introduces a generic dependency--<<dependency> << Span class= "Hljs-name" >groupid>org.springframework.boot</ groupid> <artifactid>spring-boot-starter-web</artifactid> </ dependency> </DEPENDENCIES>      

We can mvn dependency:tree view the project's dependency tree by


Dependency Tree of the project


Write a simple controller

PackageCom. Panlingxiao. springboot. Web. Controller;ImportOrg. springframework. Beans. Factory. annotation. Value;ImportOrg. springframework. Web. bind. annotation. requestmapping;ImportOrg. springframework. Web. bind. annotation. Restcontroller;/** * Restcontroller is a new feature of Spring 4.0 that uses its annotations to indicate that the current class is a @controller, and that the return value of the method marked with the @requestmapping is considered to be used by default * The @responsebody, so it is no longer processed using view resolution, * Instead, the content is returned to the client through the HTTP response body. */@Restcontrollerpublic class Hellocontroller {/** * Spring boot automatically reads application.properties, * and injects it as a system parameter, and the user can manually inject it via-dname=xxx when the application is launched, and manual injection overrides the parameters in the configuration file * If no value is specified, then the default value for name is world. */@ Value ("${Name: World}") private String name; /** * Due to the use of @restcontrolelr, it is not necessary to use @responsebody to label the returned results */@ requestmapping ("/Hello") public String SayHello () { return String. Format ("hello:%S", name);}}      

To write a spring boot class

package com.panlingxiao.springboot.web;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class WebApp{ public static void main(String[] args) { SpringApplication.run(WebApp.class, args); }}

So far, our web application has been built, just start WebApp. After the app is launched, the following information is output.


Start the log. png

The results returned by the request in the browser are as follows:


Response result. png

This Hello world example is simple, but we should be able to see the power of Spring boot. We no longer have to write Dispatcherservlet in Web. XML, no need to write the corresponding spring configuration file, no need to find the corresponding Maven dependencies, and all this is done with just a few simple annotations.

2.2 Launch the app at the command line

In addition to the ability to start the Spring boot app in the IDE, Spring Boot officially provides another way for us to complete the application launch at the command line.
By enteringmvn spring-boot run


The command line starts the result. png2.3 Create a runnable jar

The above command-line approach allows the Web app to start, but its start-up relies on maven. When we deploy the application to the server, we usually do not install MAVEN separately on the server, but just want it to start in a single jar package. Before that, if we wanted a service to run individually as a jar package, then I needed to introduce a number of plugins in the Pom file, such as a copy of a resource file, a separate jar of project dependencies to create a directory, a running main program, and so on. This sequence of operations requires MAVEN-based plug-ins to complete. Now, Spring boot gives us a plug-in for a packaged jar, and we just need to introduce it and then use it to get mvn clean package everything done.
In the original Pom file, add the following content:

<build> <plugins> <PLUGIN&G T <!--the packaged plug-in provided by Spring boot, automatically generates a running class, and binds the jar that the project relies on together with the jar package at all output. --<groupid>org.springframework.boot </groupid> < artifactid>spring-boot-maven-plugin</ artifactid> </plugin> </plugins> </build                 

Package output results. png
Menifest results. png


Now we can java -jar xxx.jar do a Web launch by doing it.


Start the results in Java application Mode. png2.4 simple understanding of Spring boot's Hello World

The above program is simple, but we do not analyze why the use of such a few lines of code can be a Web application launch, if you do not understand the reason, the individual feel that everything is useless, because you just know how to do, rather than know why to do so. The following is a simple analysis of the webapp we have written this class why it can be completed a Web application launch.

@SpringBootApplicationpublic class WebApp{    public static void main(String[] args) { SpringApplication.run(WebApp.class, args); }}

First we see that this class uses the @springbootapplication annotation for identification. This annotation is actually identified by 3 other annotations, namely @configuration, @EnableAutoConfiguration, @ComponentScan.


Springbootapplication source. png

(1). @Configuration: Its role is to identify the current class is the source of a bean definition information, it can be loaded by Spring applicationcontext processing, its role is equivalent to our previous use of the XML file, It is just that we previously configured the bean definition in XML, and now we are writing the bean's definition all based on code in the class identified by using @configuration.
Below, we illustrate the role of @configuration more clearly through an example.

public class User {    private String name;    public String getName() { return name; } public void setName(String name) { this.name = name; }}

With the class identified by @configuration, you can complete the definition of the bean information:

/** * use @ The configuration identifier * is called by the spring Appplicationcontext to generate the Bean object in the current class through  @Bean annotation. */ @Configuration public class appconfig { @Bean public User getUser () {User user = new user (); return User;}}            
public class App {    public static void main(String[] args) { /* * 将@Configuraion所标识的类通过Spring的上下问进行加载,从而实现Bean的创建。 */ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); User user = ctx.getBean("user", User.class); String value = user.sayHello(); }}

From the above example, we should be able to see @configuration and XML is almost an equivalent relationship, the role of the same, in our example above, in fact webapp this class can not use @configuration to standard, and does not affect the normal startup of the program.

(2). @EnableAutoConfiguration: This annotation allows spring to automatically infer the current running environment (judging whether a Web application is a common Java application) based on the classes that exist in the current classpath. Then, according to the specific environment to create the corresponding bean, add it to the spring ApplicationContext. For example: We added Tomcat-embedded.jar in classpath, so it will automatically help us to automatically create a embeddedservletcontainerfactory. If this object is not available, then our Tomcat cannot be started. We changed the WebApp to the following result:

//不再设置EnableAutoConfiguration会导致应用启动失败@Configuration@ComponentScanpublic class WebApp {    public static void main(String[] args) { SpringApplication.run(WebApp.class, args); }}

The Enableautoconfiguration startup result is missing. png


From the above analysis results we can, @EnableAutoConfiguration the corresponding configuration spring boot application is very important, if missing this annotation, it is very likely because of the lack of the required bean to cause the application to fail to start.

(3). @ComponentScan: This annotation is to let the spring container automatically based on the specified package and the component in the child package to find and then create, if not specified in which package to look for, then the current use of the annotation is the same package as the root of the lookup to find. It is found in the package and its sub-packages where the class is WebApp. Note: Here I define hellocontroller in the child package of the package where the WebApp is located, if the package they are in does not have the lookup relationship described above, then the controller will not be created, even if the application can start, but the result of the final response will be 404.

We used the Springapplication class in the main method to complete the launch of the application, which is a spring application-initiated Boot tool class that maintains the spring container at the bottom. Due to the limited space, spingapplication specific guidance process is no longer detailed here, I will in the following notes to record the details of how to complete the creation of the spring container springapplication, how to complete the launch of the Web application.

2.5 supplement

Springboot In addition to providing powerful features, the official also provides a very humane support, we can visit https://start.spring.io/, on the site according to the characteristics of our application, automatically its corresponding to generate spring boot template files.

At this point, Spring Boot's introductory notes are written here, and the next section will analyze Springapplication's magical things to see how it works.

Spring Boot Learning Note 1 Start your web App in the first 3 minutes of---experience

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.