Spring-boot:6 minute mastering Springboot Development

Source: Internet
Author: User
Tags build gradle

Building projects

From a technical point of view, we will use spring MVC to process Web requests, define Web views with thymeleaf, and use spring Data JPA to persist the reading list to the database, first using an embedded H2 database.

1, the project to build Spring IO website

We can go to Spring's official website: http://start.spring.io/
After entering the website, you can quickly build a spring boot base project, where you can select a MAVEN project or Gradle project and then set up the project-related configuration.

The corresponding zip file is generated when you select Generate project to download the item. Next, simply unzip the zip file and add it to the IDE.


Idea Quick Build

In addition to the initial project on the Springio website, you can also build the project through idea. As shown, the construction of the project is also quoted http://start.spring.io/

In subsequent pages, we can set up the relevant configuration information, some common dependencies, can also be initialized.



Spring Boot CLI

In addition to the common project creation methods above, we can also create projects through the CLI:

Spring init-dweb,data-jpa,h2,thymeleaf--build Gradle readinglist

  

The init command of the CLI cannot specify the project root package name and project name. The package name is demo by default and the project name is demo by default.

2. Directory structure

Regardless of the way we create a project, after importing the project into the IDE, we can see that the entire project structure follows the layout of a traditional Maven or Gradle project, where the main application code is located in the Src/main/java directory and resources are src/main/ Resources directory, the test code is in the Src/test/java directory. There are no testing resources at the moment, but if so, put them in the src/test/resources.

File Description:
    • springbootwebapplication: The application's Startup boot Class (Bootstrap Class), which is also the primary spring configuration class.
    • appliction.properties: Properties for configuring applications and spring Boot
    • springbootwebapplicationtests: A basic integration Test class.
    • Pom.xml: Project dependent files

3. Introduction of documents

Springbootwebapplication


The application class has two roles in the Spring boot application: Configuration and Boot boot.


Import org.springframework.boot.SpringApplication; Import  -- turn on component scan and automatically configure publicclass  springbootwebapplication { public Static void Main (string[] args) {Springapplication.run (springbootwebapplication. class, args); -- responsible for starting the bootstrap application}}


When we were developing with spring boot, the application class was the doorway to our service, and the key to this was the annotation @SpringBootApplication * *, which actually @SpringBootApplication Three useful annotations are included:

    • @Configuration: Indicates that the class uses the spring Java-based configuration.
    • @ComponentScan: Enable component scanning so that the Web controller classes and other components that you write can be automatically discovered and registered as beans in the context of the spring application.
    • @EnableAutoConfiguration: This configuration opens the automatic configuration of Spring boot.

The use of the Main method here is to provide a bootstrap class for @enableautoconfiguration annotations that will boot the entire application.


Springbootwebapplicationtests


When the project was created we created a test class with context.

 import   org.junit.Test;  import   Org.junit.runner.RunWith;  import   org.springframework.boot.test.context.SpringBootTest;  import   Org.springframework.test.context.junit4.SpringRunner; @RunWith (Springrunner.  class  ) @SpringBootTest -- load context through Springboot  Span style= "COLOR: #0000ff" >public  class   springbootwebapplicationtests {@Test  public  void   Contextloads () {-- Test Loaded Context}}  

Application.properties

In fact, this file is optional and you can delete it without affecting the operation of the application.
We can change the program's default configuration by adding variables to the application.properties. For example:

server.port=8000Server.contextpath=springbootweb

In the code above, we modified the program's default port (8080) to use port 8000 and modified the application's project name to Springbootweb.

Original Access Address:

http://127.0.0.1:8080/

After modification:

http://127.0.0.1:8000/SpringBootWeb/


In addition, you can configure a range of settings such as variable settings for multiple environments:

spring.profiles.active = Dev

Pom.xml


In the code listing, we refer to spring-boot-starter-parent as the top level, so that we can take advantage of Maven's dependency management capabilities, integrate many common library dependencies, and do not need to know the version. In addition to this, we have used the initial dependencies mentioned in the opening, and we only need to introduce the dependency of spring-boot-starter-web, we can use the common package in the Web.

<Parent><groupId>Org.springframework.boot</groupId><Artifactid>Spring-boot-starter-parent</Artifactid><version>1.5.7.RELEASE</version><RelativePath/> <!--Lookup parent from repository -</Parent><Dependencies><Dependency><groupId>Org.springframework.boot</groupId><Artifactid>Spring-boot-starter-web</Artifactid></Dependency>...</Dependencies>


As shown in the Spring-boot-starter-web dependency we used, we have integrated common MVC json and other dependencies.

Org.springframework.boot:spring-boot-starter-web:jar:1.5.7.release:compile[info] | +-Org.springframework.boot:spring-boot-starter-tomcat:jar:1.5.7.release:compile[info] | | +-Org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.20:compile[info] | | +-Org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.20:compile[info] | | \-Org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.20:compile[info] | +-Org.hibernate:hibernate-validator:jar:5.3.5.final:compile[info] | | +-Javax.validation:validation-api:jar:1.1.0.final:compile[info] | | \-Com.fasterxml:classmate:jar:1.3.4:compile[info] | +-Com.fasterxml.jackson.core:jackson-databind:jar:2.8.10:compile[info] | | +-Com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile[info] | | \-Com.fasterxml.jackson.core:jackson-core:jar:2.8.10:compile[info] | +-Org.springframework:spring-web:jar:4.3.11.release:compile[info] | \-Org.springframework:spring-webmvc:jar:4.3.11.release:compile[info] | \-Org.springframework:spring-expression:jar:4.3.11.release:compile 


4. Development function
4.1 Defining entity Classes Book

As you can see, the book class is a simple Java object, some of which describe the properties of the books, as well as the necessary access methods.
@Entity Note indicates that it is a JPA entity, and the id attribute is added to the @id and @generatedvalue annotations, indicating that the field
is the unique identity of the entity, and the value of this field is automatically generated.

ImportLombok. Allargsconstructor;ImportLombok. Getter;ImportLombok. Noargsconstructor;ImportLombok. Setter;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.GenerationType;Importjavax.persistence.Id;/*** Created by Weijie_huang on 2017/9/20.*/@Entity @getter@setter@noargsconstructor@allargsconstructor Public classBook {@Id @generatedvalue (strategy=Generationtype.auto)PrivateLong ID;PrivateString Reader;PrivateString ISBN;PrivateString title;PrivateString author;PrivateString description;}

4.2 Defining the Warehouse interface Readrepository

Direct inheritance of 18 common persistence operations by extension jparepository,readinglistrepository
The method. Jparepository is a generic interface with two parameters: the Realm object type for the warehouse operation, and its ID attribute
Type. In addition, I have added a Findbyreader () method to find a reading list based on the user name of the reader.

Import Com.jaycekon.demo.domain.Book; Import org.springframework.data.jpa.repository.JpaRepository; Import java.util.List; /** * Created by Weijie_huang on 2017/9/20. */  Public Interface extends Jparepository<book,long> {List<Book> findbyreader (String Reader);}

4.3 Defining the control layer Readcontroller

After you have defined the application's entity class, you persist the interface. We also need to create an MVC controller to handle HTTP requests.

Importcom.jaycekon.demo.dao.ReadRepository;ImportCom.jaycekon.demo.domain.Book;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;Importjava.util.List;/*** Created by Weijie_huang on 2017/9/20.*/@Controller Public classReadcontroller {@AutowiredPrivatereadrepository readrepository; @RequestMapping (Value= "/{reader}", method=requestmethod.get) PublicString readersbooks (@PathVariable ("Reader") (String Reader,model Model) {List<Book> readinglist =Readrepository.findbyreader (reader);if(Readinglist! =NULL) {Model.addattribute ("Books", readinglist);}return"Readinglist";} @RequestMapping (Value= "/{reader}", method=requestmethod.post) PublicString addtoreadinglist (@PathVariable ("Reader") {book.setreader (reader); Readrepository.save (book);return"Redirect:/{reader}";}}


The @controller annotation is used so that the component scan automatically registers it as
A bean in the spring application context. The warehouse interface is injected into the control class via @autowired.


4.4 Starting the Service

After the development is complete, we go to the application class and start the main method. You can start the application and then go to the following page (the HTML file is not described in detail and can be understood by viewing the source code). As you can see, our service has been successfully started.

4.5 Process Analysis


You might wonder why we didn't configure the database information, but we didn't report the exception. We clearly created the Readrepository database interface, if there is no datasource, it should be reported abnormal. But spring boot cleverly avoids the problem.

First we need to know about spring-boot-autoconfigure this dependency package. This jar package contains a lot of configuration classes. For example, THYMELEAF,JPA and the related configuration of MVC.

This is mainly related to the condition interface, the role of the interface is that only after a certain condition is reached, the bean is instantiated.

Annotations:

    • @ConditionalOnBean configured with a specific bean
    • @ConditionalOnMissingBean not configured with a specific bean
    • @ConditionalOnClass Classpath have the specified class
    • The specified class is missing from the @ConditionalOnMissingClassClasspath
    • Evaluates to true @ConditionalOnExpression given spring expression Language (spel) expressions
    • @ConditionalOnJava Java version to match a specific value or a range value
    • The jndi position given in the @ConditionalOnJndi parameter must exist, and if no argument is given, a Jndi
    • @ConditionalOnProperty the specified configuration property to have an explicit value
    • There's a designated resource in the @ConditionalOnResource classpath.

All of the above procedures do not perform database operations, the main can refer to the corresponding configuration of the Datasourceautoconfiguratio class.

@Configuration @conditionalonclass ({DataSource. class, Embeddeddatabasetype. class }) @EnableConfigurationProperties ({datasourceproperties. class }) @Import ({registrar. class, Datasourcepoolmetadataprovidersconfiguration. class })publicclass

As you can see, this bean is instantiated only after the DataSource class is instantiated. We can see that Jdbctemplateconfiguratio also has a similar situation to look at.

What you see here is just the tip of the iceberg of datasourceautoconfiguration, and Spring boot provides other self-
The dynamic configuration class also has a lot of knowledge not mentioned. However, this is sufficient to illustrate how Springboot can be configured automatically with conditional configuration.

Automatic configuration makes the following configuration decisions, which are closely related to the previous example.

-because there is H2 in the classpath, an embedded H2 database bean is created, and its type is
The JAVAX.SQL.DATASOURCE,JPA implementation (Hibernate) requires it to access the database.

-Because Classpath has an entity manager for Hibernate (introduced by Spring Data JPA delivery), it is automatically configured
Hibernate-related beans are configured, including Spring's localcontainerentitymanager-
Factorybean and Jpavendoradapter.

-Because the classpath has spring Data JPA, it is automatically configured to create a warehouse implementation based on the interface of the warehouse.

-Because Classpath has thymeleaf, Thymeleaf is configured as a view of spring MVC, including a
Thymeleaf template parser, template engine, and view parser. The view resolver resolves the classpath root relative to the
The template in the/templates directory of the directory.

-Because Classpath has spring MVC (thanks to web start-up dependencies), it configures Spring's
Dispatcherservlet and enable Spring MVC.

-Because this is a spring MVC Web application, it registers a resource handler, with respect to the CLASSPATH
The static content in the/static directory of the root directory is provided. (This resource processor can also handle/public,/resources
and/meta-inf/resources static content. )

-Because Classpath has Tomcat (which relies on the web to pass a reference), an embedded Tomcat is launched
container, monitor port 8080.

Summarize

With spring Boot's start-up and auto-configuration, you can develop spring applications more quickly and easily. The start-up relies on helping you focus on the type of functionality your application needs, rather than providing specific libraries and versions of that functionality. At the same time, auto-configuration frees you from the configuration of the model. These configurations are very common in spring applications that do not have spring boot.

While automatic configuration is convenient, some of these uses are somewhat arbitrary when developing spring applications. What if you want or need to be different when you configure spring? In the 3rd chapter, we'll see how to override Spring boot autoconfiguration to achieve some of the application's goals, and how to use similar techniques to configure its own application components.

GitHub Address: Https://github.com/jaycekon/SpringBoot

Spring-boot:6 minute mastering Springboot Development

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.