Ultra-detailed Spring boot entry notes

Source: Internet
Author: User
Tags dashed line dname xml attribute ruby on rails

1. Spring Boot Starter
Spring boot is a newer project in the spring community. The purpose of the project is to help developers create spring-based applications and services more easily, allowing more people to get started with spring faster, and to enable Java development to achieve the same productivity as Ruby on rails. Provides a fixed, convention-better framework than the configuration style for the spring ecosystem.
Spring Boot has the following features:

Provides a faster start-up experience for spring-based development

Out-of-the-box, no code generation, and no XML configuration. You can also modify the default values to meet specific requirements.

Provides some of the most common non-functional features in large projects, such as embedded servers, security, metrics, health detection, external configuration, and more.

Spring boot is not an enhancement to spring functionality, but rather a way to quickly use spring.

1.1 Simple Examples
Start by creating a generic Maven project that has a pom.xml and basic src/main/java structure.

1.1.1 Pom.xml File

<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.nes.spring.boot</groupId> <artifactId> springbootdemo1</artifactid> <version>0.0.1-SNAPSHOT</version> <parent> <groupId> Org.springframework.boot</groupid> <artifactId>spring-boot-starter-parent</artifactId> < version>1.3.0.release</version> </parent> <dependencies> <dependency> <groupid& Gt;org.springframework.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> </ dependency> </dependencies> <build> <plugins> <!--Compile-<plugin&
            Gt
    <groupId>org.apache.maven.plugins</groupId>        <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.7</source> <target>1.7</target&
            Gt
            </configuration> </plugin> <!--spring boot mavenplugin---<plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-plugin</ Artifactid> <dependencies> <dependency> <groupid>org.
                    Springframework</groupid> <artifactId>springloaded</artifactId>
        <version>1.2.5.RELEASE</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>

1.1.2 Description of the Pom
The first is increased, the addition of parent Pom is relatively simple, and Spring-boot-starter-parent contains a large number of well-configured dependency management, do not need to write the version number when you add these dependencies to your project.
Using parent pom is simple, but there are cases where we already have a parent pom that cannot be added directly when you can do this by:

<dependencyManagement>
    <dependencies>
        <dependency>
            <!--Import dependency Management from Spring Boot--
            <groupId>org.springframework.boot</groupId>
            <artifactid >spring-boot-dependencies</artifactId>
            <version>1.2.3.RELEASE</version>
            <type >pom</type>
            <scope>import</scope><!-This place--
        </dependency>
    </ Dependencies>
</dependencyManagement>

1.1.3 About Java.version Properties
The above pom.xml Although this attribute does not appear, here to special remind.
Spring uses jdk1.6 by default, and if you want to use jdk1.8, you need to add java.version to the Pom.xml attribute, as follows:

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

1.1.4 adding Spring-boot-starter-web dependencies
Spring supports a specific feature by adding a dependency such as spring-boot-starter-*.
Our example is ultimately to implement Web functionality, so this dependency is added.
A more complete list of features can be viewed: using-boot-starter-poms

1.1.4 Add Spring-boot-maven-plugin plugin
The plug-in supports a variety of functions, commonly used in two, the first is to package the project as an executable jar package.
Executing the MVN package at the root of the project will generate an executable jar that contains all the dependent jar packages, and it is convenient to run the program with just one jar package. The command also retains a XXX.jar.original jar package that contains a separate part of the project.
After the executable jar package is generated, the project can be started by executing Java-jar xxxx.jar at the command line.
Another command is MVN Spring-boot:run, which can start the project directly using Tomcat (default).
In our development process, we need to change frequently, in order to avoid repeating the startup project, we can enable the hot deployment.

1.1.6 spring-loaded Hot deployment
The spring-loaded project provides a powerful thermal deployment feature, adding/removing/modifying methods/Fields/interfaces/enumerations and other code can be hot deployed, fast, very convenient.
It is very simple to use this feature in spring boot, which is to add dependencies under the Spring-boot-maven-plugin plugin:

<!--  support for hot deployment-
<dependency>
    <groupId>org.springframework</groupId>
    < artifactid>springloaded</artifactid>
    <version>1.2.5.RELEASE</version>
</ Dependency>

Once added, the hot deployment is supported with MVN spring-boot:run boot.
Note: When using a hot deployment, you need the IDE to compile the class to take effect, you can turn on the automatic compilation function, so that when you save the changes, the class will automatically reload.

1.2 Creating an application class
We create a application class:

@RestController
@EnableAutoConfiguration Public
class Application {

@RequestMapping ("/") String Home () {
    return "Hello world!";
    }
@RequestMapping ("/now") String hehe () {
    return "now Time:" + (new Date ()). toLocaleString ();
public static void Main (string[] args) {
    springapplication.run (application.class, args);
    }
}

1.2.1 Note
Spring Boot recommends that the primary configuration class where our main method resides is configured under the root package name.

COM
 +-Example
     + myproject
         +-Application.java +-
         domain
|   +-Customer.java
|   +-Customerrepository.java
         +-service
|   +-Customerservice.java
         +-Web
             +-Customercontroller.java

There is a main method in Application.java.
Because of default and package-related annotations, the default package name is the package in which the current class resides, such as @componentscan, @EntityScan, @SpringBootApplication annotations. (both are the current Application.java package as scan scanning)

1.2.2 @RestController
Because our example is to write a Web application, so write this annotation, which is equivalent to adding @controller and @responsebody annotations at the same time.

1.2.3 @EnableAutoConfiguration
Spring boot suggests that there is only one class with that annotation.
@EnableAutoConfiguration role: Spring boot automatically configures items automatically based on the dependencies of your jar packages.
For example, if you have hsqldb dependencies under your project, Spring boot will create the default data source datasource for the in-memory database, and if you create datasource,spring boot yourself, you will not create a default datasource.

If you do not want spring boot to be created automatically, you can configure the annotation's Exclude property, for example:

@Configuration
@EnableAutoConfiguration (Exclude={datasourceautoconfiguration.class})
publicclassmyconfiguration {
}

1.2.4 @SpringBootApplication
Because a large number of projects are added on the primary configuration class
@Configuration, @EnableAutoConfiguration, @ComponentScan three annotations.
Spring Boot therefore provides the @springbootapplication annotation, which replaces the above three annotations (implemented using spring annotation inheritance).

1.2.5 Startup Project Springapplication.run
The simplest way to start a spring boot project is to do the following:
Springapplication.run (Application.class, args);
The method returns a ApplicationContext object, The specific type returned when using annotations is Annotationconfigapplicationcontext or Annotationconfigembeddedwebapplicationcontext, which is the second when the web is supported.

In addition to this method above, you can also use the following method:

Springapplication application = new Springapplication (application.class);
Application.Run (args);

Springapplication contains some other configurable methods that you can use in this way if you want to do some configuration.

In addition to the direct method above, you can also use Springapplicationbuilder:

New Springapplicationbuilder ()
        . Showbanner (False)
        . Sources (Application.class)
        . Run (args);

When using SPRINGMVC because of the need to use sub-containers, you need to use the Springapplicationbuilder, the class has a child (XXX ...) method to add a child container.

1.3 Run
Directly execute the main method directly in the IDE, and then access the http://localhost:8080.
You can also use the mvn mentioned above, you can package it as an executable jar package, and then execute the Java-jar Xxx.jar.
or execute MVN spring-boot:run run the project.

2. Spring Boot Property Configuration and use
Spring Boot allows you to use the code of the same application in different environments through external configuration, simply by using a configuration file to inject properties or to modify the default configuration.

2.1 Spring Boot supports multiple external configuration methods
These methods are prioritized as follows: command-line arguments from Jndi properties of Java:comp/env Java System Properties (System.getproperties ()) Operating system environment variables Randomvaluepropertysource configured random.* property value Application-{profile}.properties or application.yml outside the jar package (with Spring.profile Application-{profile}.properties or Application.yml (with Spring.profile) profile inside the configuration file jar package Application.properties or Application.yml (without spring.profile) configuration file outside the jar package The application.properties or application.yml (without spring.profile) configuration file inside the jar package @Configuration the @propertysource on the annotation class The default property specified by Springapplication.setdefaultproperties

2.1.1 Command-line arguments
Pass parameters by Java-jar app.jar–name= the "Spring" –server.port=9090 way.
The parameters are passed in the form of –xxx=xxx.
The parameters that can be used can either be defined by us, or they can be the default parameters in spring boot.
A lot of people might be concerned about how the Web port is configured, these are the parameters provided in spring boot, and some of the available parameters are as follows:

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file ( Default classpath:logback.xml for Logback)
logging.level.*= # levels for loggers, e.g. " Logging.level.org.springframework=debug "(TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# EMBEDDED SERVER CONFIGURATION (serverproperties)
server.port=8080
server.address= # bind to a specific NIC
Server.session-timeout= # Session Timeout in seconds
server.context-parameters.*= # Servlet Context init parameters, e.g. Server.context-parameters.a=alpha
server.context-path= # The context path, defaults to '/'
Server.servlet-path= # The servlet path, defaults to '/'

For more common application properties, please visit here
Note: command-line arguments are behind App.jar.
Command-line configuration can be disabled by springapplication.setaddcommandlineproperties (false).

2.1.2 Java System Properties
Note the Java System attribute location java-dname= "isea533"-jar App.jar, the properties that can be configured are the same, with different precedence.
For example java-dname= "isea533"-jar app.jar–name= "spring!" The name value is spring!

2.1.3 Operating system environment variables
You should know this one if you have configured the Java_home.
Here are some things to note that some OS can not be used. This name, such as Server.port, can be configured using Server_port.

2.1.4 Randomvaluepropertysource
Where a random number is used in the system, for example:
my.secret= random.valuemy.number= {random.value} my.number={random.int}
my.bignumber= random.longmy.number.less.than.ten= {Random.long} my.number.less.than.ten={random.int (10)}
MY.NUMBER.IN.RANGE=${RANDOM.INT[1024,65536]}
The random.int* supports the value parameter and the Max parameter, which is the minimum value when the max parameter is supplied.

2.1.5 Application configuration file (. properties or. yml)
Write directly in the configuration file:

name=isea533
server.port=8080

configuration files in. yml format such as:

name:isea533
  server:
    port:8080

When prefixed, a configuration file using the. yml format is simpler. About the. YML configuration file usage See here
Note: When using. YML, there must be a space between the value of the property name and the colon, such as name:isea533 correct, name:isea533 is wrong.

2.1.5.1 Location of the property configuration file
Spring will look for application.properties or application.yml from the/config directory under Classpath or from the root of classpath.
/config priority over Classpath root directory

2.1.6 @PropertySource
This annotation can specify a specific property profile with a lower priority.

2.1.7 springapplication.setdefaultproperties
For example:

springapplication application = new Springapplication (application.class);
map<string, Object>defaultmap = new hashmap<string, object> ();
Defaultmap.put ("name", "Isea-blog");
It can also be the Properties object Application.setdefaultproperties (Defaultmap);
Application.Run (args);
2.2 Apply (use) attribute 2.2.1 @Value ("${xxx}") This is the simplest way to inject property values through @Value annotations. 2.2.2 @ConfigurationProperties Spring Boot makes it easy to inject attributes into a configuration object. For example: my.name=isea533 my.port=8080 my.servers[0]=dev.bar.com my.servers[1]=foo.bar.com corresponding object: @ConfigurationProperties ( Prefix= "my") publicclassconfig {private String name; private Integer port; private list<string> servers = Newarrayl
Ist<string> ();
    Public String Gename () {returnthis.name;
    } public Integer Geport () {returnthis.port;
    } public List<string>getservers () {returnthis.servers; }
}

Spring Boot automatically injects the prefix= "my" prefix into my properties.
Spring Boot automatically converts the type, and when using list, you need to be aware that the list is initialized in the configuration.
Spring Boot also supports nested attribute injection, such as:

name=isea533
jdbc.username=root
jdbc.password=root
...

The corresponding configuration class:

@ConfigurationProperties
publicclassconfig {
private String name;
PRIVATEJDBCJDBC;
    Class Jdbc {
private String username;
private String password;
Getter ...
    }
Public Integer Geport () {
returnthis.port;
    }
Publicjdbcgetjdbc () {
returnthis.jdbc;
    }
}

The properties that begin with JDBC are injected into the JDBC object.

2.2.3 using @configurationproperties on the @bean method
For example:

@ConfigurationProperties (prefix = "foo")
@Bean
publicfoocomponentfoocomponent () {
    ...
}

Spring Boot will inject the attributes that begin with Foo into the Foocomponent object by name matching.

2.2.4 Property Placeholder
For example:

App.name=myapp
App.description=${app.name} is a Spring Boot application
The previously configured properties can be referenced in the configuration file (the priority is configured here to work). The default
value can also be set by using the ${app.name: Default name} method, which uses the default property when the referenced property is not found.
because the ${} approach is handled by MAVEN. If your Pom inherits the Spring-boot-starter-parent,
Spring boot has changed the maven-resources-plugins default ${} to the @ @ method, such as @name@.
If you are introducing spring Boot, you can modify the delimiter using the other

2.2.5 can also shorten command parameters by using property placeholders
For example, modifying the Web default port requires the use of the –server.port=9090 method if it is written in the configuration:

server.port=${port:8080}

You can use a shorter –port=9090 and use the default value of 8080 when you do not provide this parameter.

2.2.6 property name matching rules
For example, you have the following configuration objects:

@Component
@ConfigurationProperties (prefix= "person")
publicclassconnectionsettings {
private String FirstName;
}

FirstName can use the following property names:
Person.firstname, the standard hump-type naming
Person.first-name, dashed line (-) Split method, recommended for use in. Properties and. Yml Configuration Files
Person_first_name, uppercase underline form, recommended for use in system environment variables

2.2.7 Property Validation
You can use JSR-303 annotations for validation, such as:

@Component
@ConfigurationProperties (prefix= "Connection")
publicclassconnectionsettings {
@NotNull
privateinetaddressremoteaddress;

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.