Ten Characteristics of Springboot springapplication

Source: Internet
Author: User
Tags log log

1. Failed to start

If you fail to start the project, you register FailureAnalyzers to get error messages and workarounds. For example, if the 8080 port where you launched the application is occupied, you will see the following information:

application FAILED to START***************************8080 inch Use . Action:identify and stop the processthat'slistening on port 8080 or configure this application to list En on another port.

Spring Boot provides a number of FailureAnalyzer implementation classes, and you can implement one yourself.

You can also enable except by opening the Debug property or configuring Org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer in the log log Ion is much easier to understand.

Open the Debug property to start the command and add--debug

$ java-jar myproject-0.0. 1-snapshot.jar--debug

2. Custom Banners

The banner at boot time can be classpath by adding a banner.txt below, of course, you can also specify the file encoding via the banner.location of the properties file and the Banner.charset file (default UTF-8). You can also replace the banner with a picture by adding banner.png, Banner.gif, banner.jpg under Classpath, or set the property to banner.image.location the specified picture, and the picture will be converted to text.

Inside the banner you can use the following properties with the El Expression:

${application.version} MANIFEST. The version number in the MF file, such as implementation-version:1.0, will be printed as 1.0

${application.formatted-version} is also the print version number, but the version number is preceded by a V

${spring-boot.version} springboot version

${spring-boot.formatted-version} is also the Springboot version, preceded by a V

${application.title} MANIFEST. MF defines the application name, such as Implementation-title:myapp, that will print the MyApp

You can also pass Springapplication.setbanner (...?). Way to set the banner, implement the Printbanner () method of the Org.springframework.boot.Banner interface to generate your banner.

You can set the banner display or not (Log,off) by setting the Spring.main.banner-mode property.

3, Custom Springapplication

If the official springapplication does not suit your tastes, you can customize one, for example, close banner you can write:

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

The arguments passed to Springapplication by the constructor are Springbeans project configurations, and in most cases you can refer to the @configuration class or the XML being scanned.

These can also be configured through the properties file, which is described later.

4. Fluent Builder API

If you need to build a multi-tier applicationcontext (context for multiple parent-child relationships), you can use the fluent Builder API, which is implemented with class Springapplicationbuilder. For example:

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

Read more about Springapplicationbuilder's API documentation: https://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/api/org/ Springframework/boot/builder/springapplicationbuilder.html

5. Application Events and listeners

In addition to springframework common eventsContextRefreshedEvent外,SpringApplication也添加了很多事件。

Many events are triggered before springapplication is created, so you cannot register listeners with these events in the form of beans.

Can you pass Springapplication.addlisteners (...?) Or Springapplicationbuilder.listeners (...?) method to register them.

If you want your listener to be created automatically and not affected by the creation of springapplication, you can add meta-inf/to your project Spring.factories the file and sets the value of Org.springframework.context.ApplicationListener as the Listener class, as follows:

Org.springframework.context.applicationlistener=com.example.project.mylistener

The following are common events:

The applicationstartingevent is triggered after the app starts, listeners, and initializers before registering.

Applicationenvironmentpreparedevent is triggered before the context is ready to be used before the environment is started.

Applicationpreparedevent after a refresh, the defined bean is loaded.

Applicationreadyevent all callback functions are executed after the refresh and the application is ready for the corresponding request.

The Applicationfailedevent application throws an exception trigger at startup.

6. Web Environment variables

Springapplication will try to establish the right applicationcontext to protect your interests. By default, you start Annotationconfigapplicationcontext or annotationconfigembeddedwebapplicationcontext based on whether you start in a development environment.

The method of judging the environment variables is quite simple (judging by a few classes), which you can set directly by Setwebenvironment (Boolean webenvironment).

7. Parameters

If you want to give Springapplication.run (...?) Pass in the parameters, you can inject the Org.springframework.boot.ApplicationArguments object, Applicationarguments provides access to the string[] parameter, as follows:

 import  org.springframework.boot.*import  org.springframework.beans.factory.annotation.*import  Org.springframework.stereotype.* @Component   Public  class   Mybean {@Autowired  
   
    public  
     Mybean (applicationarguments args) { 
    
     boolean  debug = args.containsoption ("Debug" 
      <String> files = Args.getnonoptionargs ();  //  If run with "--debug logfile.txt" debug= True, files=["LogFile.txt"]  }}  
    
   

You can also register Commandlinepropertysource and inject parameters by @value annotations.

8, Applicationrunner or Commandlinerunner

If you need to execute some code after springapplication startup, you can implement Applicationrunner or Commandlinerunner. Both of these methods execute the Run method after the Springapplication run method finishes executing.

Import org.springframework.boot.*import org.springframework.stereotype.*@Component  Public class Implements Commandlinerunner {    publicvoid  run (String ... args) {        // do something ...     }}

You can invoke the corresponding applicationrunner in a particular code by implementing the Org.springframework.core.Ordered interface or by using Org.springframework.core.annotation.Order annotations or a commandlinerunner bean.

9. Springapplication Application Exit

Each of the Springapplication registers a program-closed hook in the JVM to ensure that the application gracefully shuts down. All spring Standard Life-cycle functions, such as the Disposablebean interface, or @predestroy, are executed.

You can do this by implementing the Org.springframework.boot.ExitCodeGenerator interface. The interface will return a specific status code, and when Springapplication.exit () is called, it will be returned as a status code.

@SpringBootApplication Public classexitcodeapplication {@Bean Publicexitcodegenerator Exitcodegenerator () {return NewExitcodegenerator () {@Override Public intGetexitcode () {return42;    }        }; }     Public Static voidMain (string[] args) {system.exit (springapplication. Exit (Springapplication.run (Exitcodeapplica tion.class, args)); }}

The Exitcodegenerator interface is the interface that exits the exception call.

10. Admin

The admin-related feature of Springapplication can be opened through the property spring.application.admin.enabled, which will be exposed on the Mbeanserver platform Springapplicationadminmxbean interface. You can use this to manage the springapplication remotely.

If you want to know which port it is running on, you can query the value of the property Local.server.port.

Ten Characteristics of Springboot springapplication

Related Article

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.