Spring boot-(3) Spring boot feature 1

Source: Internet
Author: User

This section will delve into the details of spring boot to learn the main features of the spring boot that you want to use or customize.

1. Springapplication

The Springapplication class provides a convenient way to guide a spring application, which is opened from the main method. Typically, you can springapplication.run methods by using static methods, as follows:

 Public Static void Main (string[] args) {Springapplication.run (myspringconfiguration.  Class, args);}
View Code

When the app launches, you can see output similar to the following, by default, the log information for the info level will be displayed, including the relevant boot details, such as the user who launched the app:

. ____ _ _ _ _/\\/___ _ _ _ _ (_) _ __ _ \ \ \ (() \___ | ' _ | ' _| | ' _ \ _ ' | \ \ \  \\/  ___)| |_)| | | | | ||  (_| | ))) ' |____|. __|_| |_|_| |_\__, | ////=========|_|==============|___/=/_/_/_/:: Spring Boot:: v2.0.0.build-snapshot2013-07-31 00:08:16.117 INFO 566 ---[main] o.s.b.s.app.sampleapplication:starting sampleapplication v0.1.0 on MyComputer with P ID 56603 (/apps/myapp.jar started by Pwebb) 2013-07-31 00:08:16.166 INFO 56603---[main] ationconfigservletweb serverapplicationcontext:refreshing Org.springframework.boot.web.ser[email protected]6e5a8246:startup Date [ Wed Jul 00:08:16 PDT 2013]; Root of context hierarchy2014-03-04 13:09:54.912 INFO 41370---[main]. T.tomcatservletwebserverfactory:serv            Er initialized with port:80802014-03-04 13:09:56.501 INFO 41370---[main] o.s.b.s.app.sampleapplication : Started sampleapplication in 2.992 seconds (JVM Running   for3.658)
View Code(1) Failed to start

When the program fails to start, the registered failureanalyzers will have the opportunity to provide specific error messages and specific methods to fix the problem. For example, when you open a web app on port 8080 and the port is already in use, you can see similar information like this:

 This application-listen on another port.
View Code

When any error analyzer cannot handle the exception, you can still display all the authentication reports to better understand which piece of error. If you do this, you need to "Org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener" Enable the Debug property or debug log level. For example, if you use Java-jar to run a program, you can enable the Debug property by following this command:

$ Java-jar Myproject-0.0.1-snapshot.jar--debug
View Code(2) Custom banner

When you start a program, the printed banner, such as "Spring", can be modified by adding the Banner.txt file to classpath or by setting the Banner.location property to specify the location of the file. If the file is not UTF-8 encoded, you need to set Banner.charset. In addition to text files, you can also add banner.gif, banner.jpg or banner.png pictures to Classpath, or set banner.image.location properties. The image will be converted to an ASCII format for presentation and displayed on any text banner.

In the Banner.txt file, you can use the following placeholders:

Variable Meaning
${application.version} The version number of the app, as declared by MANIFEST.MF. For example: implemention-version:1.0 will show 1.0
${application.formatted-version} Similar to ${application.version}, but will be formatted with the beginning of V, such as: v1.0
${spring-boot.version} Spring boot version, such as 2.0.0.build-snapshot.
${spring-boot.formatted-version} Format the spring boot version with the beginning of V, such as V2.0.0.build-snapshot
${ansi.name}, ${ansicolor.name}
${ansibackground.name},
${ansistyle.name}
The four relationships are equivalent, and name indicates the name of the ANSI transfer code
${application.title} The name of the app, as shown in MANIFEST.MF, such as: Implementation-title:myapp will print MyApp

Note: You can also set the banner information by calling the Springapplication.setbanner (Banner Banner) method, The banner can be implemented by invoking the Org.springframework.boot.Banner interface and implementing the Printbanner () method.

You can also use the Spring.main.banner-mode property to determine whether a banner is printed in the Standard Output window (console), output to a log in the configuration, or disable generation (off).

The printed banner is registered as a singleton bean object, and is under the Springbootbanner name.

(3) Custom springapplication

If the default Springapplication class does not suit your tastes, you can create a local instance and customize the instance to replace it. For example, close the banner as follows:

 Public Static void Main (string[] args) {    new springapplication (myspringconfiguration.  Class);    App.setbannermode (Banner.Mode.OFF);    App.run (args);}
View Code

You can also configure springapplication with the Application.properties file.

(4) Fluent builder API

If you need to build a applicationcontext level, or if you prefer to use the Fluent build API, you can use Springapplicationbuilder. Springapplicationbuilder lets you connect multiple method calls, and includes the parent and child methods that let you create a hierarchical relationship, as follows:

New Springapplicationbuilder (). Sources (Parent.  Class). Child (Application.  Class). Bannermode (Banner.Mode.OFF). Run (args);
View Code

Note: There are some limitations when creating the ApplicationContext hierarchy. For example, the Web component must be contained in the child context, and the same environment are used in the parent and child contexts.

(5) Apply events and listeners

In addition to the usual spring framework events such as Contextrefreshedevent, a springapplication also sends some additional events.

Note: Some events are actually triggered between applicationcontext creation, so you cannot register a listener (as @bean) on these events. But you can register by calling the Springapplication.addlisteners () or Springapplicationbuilder.listeners () method.

If you want to automatically register those listeners and ignore the way the app was created, you can add a meta-inf/to the project Spring.factories file, and reference your listener by using the Org.springframework.context.ApplicationListener property, for example:

Org.springframework.context.ApplicationListener = Com.example.project.MyListener
View Code

When the program runs, the app events are sent in the following order:

1) A applicationstartingevent will be sent at startup, but after the listener registers and initializes the process.

2) A applicationenvironmentprepareevent will be sent when the environment is used in context, but after the creation of that context.

3) A applicationprepareevent is sent before the refresh starts, but after the bean definition is loaded.

4) A applicationreadyevent is called after the refresh and any related callback processing, in order to notify the application that the service request has been prepared.

5) A applicationfailedevent will be sent if there is an exception at startup.

Note: Usually you don't use app events, but it's helpful to know that they exist. In essence, Spring boot uses events to handle many tasks.

Application events are sent through the Spring framework's event publishing mechanism. In this part of the mechanism, when an event is published to a listener in the child context, it is also published to the parent context listener. The result of this scenario is that if your app uses a hierarchy of springapplication instances, a listener might receive multiple instances of the same type of app event.

To allow your listener to differentiate an event from its own context or an event from a descendant context, it should request that its application context be injected and then compare the injected context with the context of the event. Context injection two ways to implement: 1) by implementing the Applicationcontextaware class; 2) If the listener is a bean, use the @autowired annotation.

(6) Web environment

Springapplication try to create the correct type of applicationcontext in your position. By default, Annotationconfigapplicationcontext or Annotationconfigservletwebserverapplicationcontext will be used, Depends on whether you are developing a Web application.

The algorithm that determines the Web environment is fairly simple (based on the current few classes). If you want to override the default, you can use Setwebenvironment (Boolean webenvironment).

You can also have full control over the type of ApplicationContext by calling the Setapplicationcontextclass () method.

Note: When using springapplication in JUnit unit tests, it is often required to call Setwebenvironment (false).

(7) Access to application parameters

If you want to access the application parameters in the incoming Springapplication.run () method, you can inject a org.soringframework.boot.ApplicationArguments bean. The Applicationarguments interface can provide access for native string[] parameters, as well as the option and Non-option parameters for parsing.

import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @Componentpublicclass Mybean {@ autowired public Mybean (applicationarguments args) {boolean debug = Args.containsoption ("debug "); list<string> files = Args.getnonoptionargs (); //If run with "--debug logfile.txt" debug=true, files=["LogFile.txt"]}}
View Code

Note: Spring boot also registers commandlinepropertysource with the spring environment. This allows you to inject individual application parameters by using @value annotations.

(8) using Applicationrunner or Commandlinerunner

If you want to run some special code when springapplication is turned on, you can implement Applicationrunner or Commandlinerunner interfaces. The two interfaces work the same way, providing a separate run method that will be called at the end of Springapplication.run ().

The Commandlinerunner interface provides access to the application parameter string[], Applicationrunner uses the Applicationarguments interface described earlier.

import Org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Componentpublicclassimplements commandlinerunner{publicvoidthrows Exception {}}
View Code

If more than one of the defined Commandlinerunner or Applicationrunner beans must be called in the order specified, it can be implemented in the following two ways: 1) Implement org.springframework.core.Ordered interface 2 ) Use Org.springframework.core.annotation.Order annotations.

(9) Program exit

Each springapplicaion registers a shut-off hook for the JVM to ensure that the applicationcontext exits with a peaceful shutdown. Callbacks for all standard spring lifecycles can be used, such as Disposablebean interfaces or @predestory annotations.

Also, when Springapplication.exit () is called, the Org.springframework.boot.ExitCideGenerator interface can be implemented if beans wants to return a special exit code. The exit code can then pass in System.exit () to return as a status code, as shown in the following example:

import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import Org.springframework.context.annotation.Bean; @SpringBootApplicationpublicclass exitcodeapplication {@Bean public exitcodegenerator exitcodegenerator () {return () 42;}  Public Static void Main (string[] args) {system.exit (Springapplication.exit (Springapplication.run (exitcodeapplication . ( class, args)));}}
View Code

In addition, the Exitcodegenerator interface can be used to implement exceptions. When an exception occurs, Spring boot returns an exit code that is provided based on the implementation Getexitcode () method.

(10) Management features

You can use management-related attributes by specifying the Spring.application.admin.enabled property. This will expose Springapplicationadminmxbean on the Mbeanserver platform. You can use this feature to remotely manage your Spring boot app. This feature will benefit the encapsulation implementation of the task service.

Attention:

1) If you want to know which HTTP port the current program is running on, you can get it through the Local.server.port property.

2) Use this feature with caution, because Mbean exposes methods for shutting down the application.

Spring boot-(3) Spring boot feature 1

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.