Springboot notes One

Source: Internet
Author: User
1 Start 1.1 Spring Introduction

Spring boot makes it easy to develop stand-alone, product-level based spring applications, and you only need to "just run". We provide out-of-the-box settings for the spring platform and third party libraries, so you can start methodically. Most spring boot applications require a small spring configuration.

You can use spring boot to create a Java application and use Java-jar to start it or adopt a traditional war deployment approach. 1.2 System Requirements

By default, thespring Boot 1.3.0.build-snapshot requires JAVA7 and spring framework 4.1.3 or above. You can use spring Boot under JAVA6, but you need to add additional configuration. Refer to the section 73.9 for specific reference, "How to use Java 6". The build environment is explicitly supported by maven (3.2+) and Gradle (1.12+).

servlet containers The following inline containers support unpacking (out of box):

Name      servlet version   Java version
Tomcat 8    3.1     java 7+
Tomcat 7    3.0     Java 6+
Jetty 9     3.1     java 7+
Jetty 8     3.0     Java 6+
undertow 1.1    3.1 java 7+

You can also deploy the spring boot application to any container that is compatible with the servlet 3.0+. 1.3 First Spring boot application

Before you begin, you will need to open a terminal to check whether the available Java version and Maven are installed:

$ 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

Creating Pom.xml Files

<?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>1.3.0.BUILD-SNAPSHOT</version> </parent> ;! --Additional lines to be added ...--> <!--(you don ' t need this if you are 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>

Add classpath dependencies:

Spring Boot offers a lot of "Starter POMs," which allows you to easily add jars to your classpath. Our sample program already uses spring-boot-starter-parent at the partent node of the POM. Spring-boot-starter-parent is a special starter that provides a useful maven default setting. It also provides a dependency-management node so that you can omit the version tag for "Blessed" dependencies.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

If you run MVN dependency:tree again, you'll see some other dependencies now, including the Tomcat Web server and spring boot itself.

Write code:

To complete the application, we need to create a separate Java file. MAVEN compiles the source code under Src/main/java by default, so you need to create that file structure and then add a file called 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);
    }

@RestController and @requestmapping Description:

@RestController. This is referred to as a stereotype (stereotype) annotation. It provides advice to people who read the code. For spring, the class plays a special role. In this example, our class is a Web @Controller, so when you process incoming Web requests, Spring asks for it.

@RequestMapping annotations provide routing information. It tells Spring that any HTTP request from the "/" path should be mapped to the home method. @RestController annotations tell spring to render the result as a string and return it directly to the caller.

@EnableAutoConfiguration. This annotation tells spring boot how you want to configure spring based on the added jar dependencies. Because Spring-boot-starter-web adds Tomcat and spring MVC, Auto-configuration will assume that you are developing a Web application and setting up the spring accordingly.

The Main method. This is just a standard method that follows Java's convention for an application entry point. Our main method delegates the business to the Springapplication class of spring boot by calling run. Springapplication will guide our application, start spring, and launch the automatically configured Tomcat Web server accordingly. We need to pass Example.class as a parameter to the Run method to tell Springapplication who is the main spring component.

Run:

MVN Spring-boot:run

If you use a browser to open localhost:8080, the following output:

Hello world!
To create an executable jar

In order to create an executable jar, you need to add spring-boot-maven-plugin to our pom.xml. Under the Dependencies node, insert the following:

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

Note: The Spring-boot-starter-parent pom contains configurations for binding repackage targets. If you do not use parent POM, you will need to declare the configuration yourself. Specific reference plug-in documentation.

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

MVN Package

If you look at the target directory, you should see Myproject-0.0.1-snapshot.jar. The file should have a size of around 10Mb. If you want to peek inside the structure, you can run jar TVF:

Jar TVF Target/myproject-0.0.1-snapshot.jar

In the target directory, you should also be able to see a very small file called myproject-0.0.1-snapshot.jar.original. This is the original jar file that Maven created before the spring boot repackaging.

In order to run the application, you can use the Java-jar command:

Java-jar Target/myproject-0.0.1-snapshot.jar
2. Using Spring Boot 2.1 maven

Maven users can inherit the Spring-boot-starter-parent project to get the appropriate default settings. The parent project provides the following attributes:

The default compilation level is the Java 1.6
source code for UTF-8
a dependency management node, allowing you to omit the common dependent <version> tag and inherit from Spring-boot-dependencies POM.
appropriate resources to filter the
appropriate plug-in configuration (exec plugin, surefire,git commit id,shade)
for application.properties and application.xml resource filtering

Last point: Because the default profile receives the spring-style placeholder (${...} ), Maven filtering instead of @.. @ placeholder (you can overwrite it with the Maven attribute Resource.delimiter).

To configure your project inheritance Spring-boot-starter-parent simply set up parent as:

<!--Inherit defaults from Spring Boot-->
<parent>
    <groupid>org.springframework.boot</ groupid>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0. Build-snapshot</version>
</parent>

Note: You should only specify the spring boot version on the dependency. If you import other starters, you can safely omit the version number.

using spring Boot with no parent Pom

Not everyone likes to inherit Spring-boot-starter-parent POM. You may need to use the corporate standard parent, or you may prefer to explicitly declare all MAVEN configurations.

If you do not use spring-boot-starter-parent, you can still gain the benefits of dependency management by using a scope=import dependency:

<dependencyManagement>
     <dependencies>
        <dependency>
            <!--Import dependency Management from Spring Boot-->
            <groupId>org.springframework.boot</groupId>
            <artifactid >spring-boot-dependencies</artifactId>
            <version>1.3.0.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </ Dependencies>
</dependencyManagement>

Change the Java version

Spring-boot-starter-parent Choose a fairly conservative Java compatibility policy. If you follow our advice and use the latest Java version, you can add a java.version attribute:

<properties>
    <java.version>1.8</java.version>
</properties>

* * Using the spring Boot maven plugin * *

The Spring boot contains a MAVEN plug-in that can package the project into an executable jar. If you want to use it, you can add the plugin to the node:

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

Note: If you use the Spring Boot Starter parent Pom, you only need to add the plugin without configuring it unless you want to change the settings defined in Partent. 2.2 Organization Code

Spring boot does not require any special code structure, however, here are some useful best practices.

Use the "default" package

When a class does not contain a package declaration, it is considered to be under the default package. It is not generally recommended to use default package and should be avoided. Because classes from each jar will be read for spring boot applications that use @componentscan, @EntityScan or @springbootapplication annotations, this can cause problems.

Locate main application class

We usually recommend that you place the main application class in the root package (root package) that is located above the other classes. You typically use @enableautoconfiguration to annotate your main class and secretly define a basic "search package" for some items. For example, if you are writing a JPA application, the packages that are @enableautoconfiguration annotated classes will be used to search for @entity items.

Using the root package allows you to use @componentscan annotations without having to define a Basepackage attribute. If the main class is in the root package, you can also use the @springbootapplication annotation.

The following is a typical structure:

COM
 +-Example
     +-myproject
         +-application.java
         |
         +-Domain
         |   +-Customer.java
         |   +-Customerrepository.java
         |
         +-Service
         |   +-Customerservice.java
         |
         +-Web
             +-Customercontroller.java

The Application.java file declares the main method, as well as the basic @configuration.

Package com.example.myproject;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
Import Org.springframework.context.annotation.ComponentScan;
Import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan Public
class Application {public

    static void Main (string[] args) {
        springapplication.run (application.class, args);
    }

}
2.3 Configuration Class

Spring boot advocates a java-based configuration. Although you can use an XML source to invoke Springapplication.run (), we usually recommend that you use the @configuration class as the primary source. Classes that generally define the main method are also a good candidate for the main @configuration.

1. Import other Configuration Classes

You don't need to put all the @configuration into a separate class. @Import annotations can be used to import other configuration classes. Alternatively, you can use the @componentscan annotation to automatically collect all the spring components, including the @configuration class.

2. Import XML Configuration

If you absolutely need to use an xml-based configuration, we recommend that you still start with a @configuration class. You can use additional @importresource annotations to load the XML configuration file. 2.4 Automatic Configuration

The Spring boot automatic configuration (auto-configuration) attempts to automatically configure your spring application based on the jar dependencies you add. For example, if you have hsqldb under your classpath and you have not manually configured any database connection beans, then we will automatically configure a memory (in-memory) database.

You can select automatic configuration by adding @enableautoconfiguration or @springbootapplication annotations to a @configuration class.

Note: You only need to add a @enableautoconfiguration annotation. We recommend that you add it to the main @configuration class.

Disabling a specific automatic configuration

If you find that you have applied specific automatic configuration classes that you do not want, you can disable them by using the exclusion attribute of the @enableautoconfiguration annotation.

Import org.springframework.boot.autoconfigure.*;
Import org.springframework.boot.autoconfigure.jdbc.*;
Import org.springframework.context.annotation.*;

@Configuration
@EnableAutoConfiguration (Exclude={datasourceautoconfiguration.class}) public
class myconfiguration {
}
2.5 Spring beans and Dependency injection

You are free to use any standard spring framework technology to define beans and the dependencies they inject. For simplicity, we often use @componentscan annotations to search for beans and combine the @autowired constructor injection.

If you use the proposed structure organization code (put the application class under the root package), you can add @componentscan annotations without any parameters. All of your application components (@Component, @Service, @Repository, @Controller, etc.) will be automatically registered as spring Beans.

The following is an example of a @service bean that uses builder injection to get a required riskassessor bean.

Package com.example.service;

Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;

@Service public
class Databaseaccountservice implements Accountservice {

    private final riskassessor Riskassessor;

    @Autowired public
    Databaseaccountservice (riskassessor riskassessor) {
        this.riskassessor = riskassessor;
    }

    // ...
}

Note: Note how to use builder injection to allow Riskassessor fields to be marked as final, which means that riskassessor follow-up is immutable. 2.6 using @springbootapplication annotation

Many spring boot developers always use @configuration, @EnableAutoConfiguration and @componentscan to annotate their main class. As these annotations are used so frequently (especially if you follow best practices above), Spring boot provides a convenient @springbootapplication choice.

The @springbootapplication annotation is equivalent to using @configuration, @EnableAutoConfiguration, and @componentscan with the default properties.

Package com.example.myproject;
Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication//Same as @Configuration @EnableAutoConfiguration @ComponentScan public
class Application { Public

    static void Main (string[] args) {
        springapplication.run (application.class, args);
    }


2.7 As a packaged application run

If you use the spring Boot maven or Gradle plug-in to create an executable jar, you can use Java-jar to run your application. For example:

Java-jar Target/myproject-0.0.1-snapshot.jar

It is possible to run a packaged program and turn on remote debugging support, which allows you to attach the debugger to packaged applications:

Java-xdebug-xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
   -jar target/ Myproject-0.0.1-snapshot.jar
2.8 Run with the MAVEN plugin

The Spring Boot Maven plug-in contains a run target that can be used to quickly compile and run applications. The application runs in an exposed way and you can edit the resources because of the instant "hot" loading.

MVN Spring-boot:run

You may want to use a useful operating system environment variable:

Export Maven_opts=-xmx1024m-xx:maxpermsize=128m-djava.security.egd=file:/dev/./urandom
3 Spring Boot features 3.1 springapplication

The Springapplication class provides a convenient way to start a spring application from the main () method. In many cases, you simply delegate to springapplication.run this static method:

public static void Main (string[] args) {
    springapplication.run (myspringconfiguration.class, args);

When the application starts, you should see something like the following (This is the Beast of God.) ):

. ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | ||  (_| | ) ) ) )
  '  |____| .__|_| |_|_| |_\__, |  ////=========|_|==============|___/=/_/_/_/:: Spring Boot:: V1.2.2.build-snapshot 2013-07-31 00:08:16.117 INFO 56603---[main] o.s.b.s.app.sampleapplication:starting sampleapplication v0.1.0 on MyComputer wi Th PID 56603 (/apps/myapp.jar started by Pwebb) 2013-07-31 00:08:16.166 INFO 56603---[main] ationconfigembed Dedwebapplicationcontext:refreshing Org.springframework.boot.context.embedded.annotationconfigembeddedwebapplicationcontext@6e5a8246:startup Date [ Wed 00:08:16 PDT 2013]; Root of the context hierarchy 2014-03-04 13:09:54.912 INFO 41370---[main]. T.tomcatembeddedservletcontainerfacto Ry:server initialized with port:8080 2014-03-04 13:09:56.501 INFO 41370---[main] o.s.b.s.app.sampleapplic      ation      : S
 

The info level log information is displayed by default, including some relevant startup details, such as the user who started the application. 3.1.1 Custom Banner

By adding a banner.txt or setting banner.location under Classpath, you can specify that the appropriate file changes the banner that is printed during startup. If the file has a special encoding, you can use banner.encoding to set it (default is UTF-8).

The following variables can be used in Banner.txt:

Variable          description
${application.version}          MANIFEST. The application version number declared in MF, such as 1.0
${application.formatted-version}        MANIFEST. The formatted application version number declared in MF (enclosed in parentheses and prefixed by V) for display, such as      the spring boot version number that (v1.0) ${spring-boot.version} is using, For example, 1.2.2.build-snapshot
${spring-boot.formatted-version}        is using the version number of the spring boot that is formatted (enclosed in parentheses and prefixed with V) for display, for example (V1.2.2.build-snapshot)

Note: If you want to generate a banner programmatically, you can use the Springbootapplication.setbanner (...) Method. Use the Org.springframework.boot.Banner interface to implement your own Printbanner () method. 3.1.2 Custom Springapplication

If the default springapplication does not suit your taste, you can create a local instance and customize it. For example, close banner you can write this:

public static void Main (string[] args) {
    springapplication app = new Springapplication (myspringconfiguration.class) ;
    App.setshowbanner (false);
    App.run (args);
}

Note: The constructor parameter passed to Springapplication is the configuration source for spring beans. In most cases, these will be references to the @configuration class, but they may also be XML configurations or references to scan packages. 3.1.3 Fluent Build API

If you need to create a layered applicationcontext (multiple contexts with parent-child relationships), or you just prefer to use a fluent build API, you can use Springapplicationbuilder. Springapplicationbuilder allows you to call multiple methods in a chained fashion, including parent and child methods that can create hierarchies.

New Springapplicationbuilder ()
    . Showbanner (false).
    sources (Parent.class)
    . Child (Application.class)
    . Run (args);

Note: There are some limitations in creating the ApplicationContext hierarchy, for example, the Web Component (components) must be included in the child context, and the same environment is used for the parent context as well as the child context. 3.1.4 Application events and listeners

In addition to the common spring framework events, such as Contextrefreshedevent, a springapplication also sends some additional application events. Some events are actually triggered before the ApplicationContext is created.

You can register event listeners in a variety of ways, most commonly using springapplication.addlisteners (...). Method. When your application is running, the application events are sent in the following order:

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.