SpringApplication common instructions

Starting method

Mode 1: Perform SpringApplication.run () in the main method in this way to start our project

// 方式一
@SpringBootApplication 
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

Second way: the underlying SpringApplication.run () is actually new object of a SpringApplication

// 方式二
public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MySpringConfiguration.class);
    app.run(args);
}

 

Three ways: SpringApplicationBuilder

// 方式三
public static void main(String[] args) {
    new SpringApplicationBuilder()
        .sources(Parent.class)
        .child(Application.class)
        .run(args);
}

Sometimes we need to create a multi-level ApplicationContext (for example, Spring's ApplicationContext parent-child relationship and SpringMVC), then we can use another "smooth" the official API is called to start the project, namely the use of multiple methods SpringApplicationBuilder talk calls to string together to create a multi-level ApplicationContext by parent () and child (). If you look at the underlying code, you can see that in addition to calling child () method is slightly different, and the other of the first two methods is almost the same.

 

Startup failed

If your application fails to launch, registration FailureAnalyzerswill have the opportunity to provide specific error messages and specific actions to resolve the problem. For example, if you are in port 8080start web application, and that the port is already in use, you should see something similar to the following message:

*************************** APPLICATION FAILED TO START *************************** Description: Embedded servlet container failed to start. Port 8080 was already in use. Action: Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
Spring Boot offers a number of FailureAnalyzer implementation, you can also add your own.

If no exception fault analyzer can handle, you can still display the full report, in order to better understand it correctly, to do this, you need to org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListenerenable the debug attribute or enable DEBUG logging .

For example, if you're using java -jarto run your application, you can enable the debugfollowing properties:

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

23.2 Custom Banner

Banner printing at startup can add banner.txtto your class path or set file spring.banner.locationattributes point to the location of the file. If the file is not encoded UTF-8, you can set up spring.banner.charset. In addition to a text file, you can also add a banner.gif, banner.jpgor banner.pngimage files to your class path or set spring.banner.image.locationproperties. The image is converted into ASCII art representation, and any text printed on the title.

In your banner.txtfile, you can use any of the following placeholders:

Table 23.1. Banner variable

variable description
${application.version} In the MANIFEST.MFversion number of the application declared, for example, Implementation-Version:1.0are printed as1.0
${application.formatted-version} The version number of the application, as MANIFEST.MFdeclared and formatted for display (and prefix includes the parentheses v), for example (v1.0))
${spring-boot.version} Spring Boot version you are using, for example,2.0.5.RELEASE
${spring-boot.formatted-version} Spring Boot version you are using, the format for displaying (enclosed in brackets and vprefix), e.g.(v2.0.5.RELEASE)
${Ansi.NAME}or${AnsiColor.NAME} NAMEIs the name of the ANSI escape codes. For more information, see AnsiPropertySource
${application.title} The title of your application, as stated above, in MANIFEST.MF, for example, Implementation-Title:MyAppare printed as MyApp)
If you want to programmatically generate a banner, you can use the SpringApplication.setBanner(…) method, using org.springframework.boot.Banner an interface and implement your own printBanner() method.

You can also use the spring.main.banner-modeproperty to determine whether the banner must be printed on the system System.out( console), sent to the configured logger ( log), or no generation ( off).

In the following names, banner printing is registered as a singleton bean: springBootBanner.

YAML mapped off to false , so if you want to disable the application banner, make sure you add quotation marks, as in this example:
spring: 
  main:
    banner-mode: "off"

23.3 custom SpringApplication

If SpringApplicationthe defaults do not suit your preferences, you can create a local instance and customize it, for example, to turn off the banner, you can write:

public static void main(String[] args) {
   SpringApplication app = new SpringApplication(MySpringConfiguration.class); app.setBannerMode(Banner.Mode.OFF); app.run(args); }
Passed to the SpringApplication constructor parameter is arranged Spring bean source, in most cases, these are for @Configuration reference to the class, they may be references to the XML configuration, or a reference to a packet that should be scanned.

You may also be used application.propertiesconfiguration SpringApplication, see section 24, the configuration of the external .

For information about configuring a complete list of options, see SpringApplication Javadoc .

23.4 Fluent builder API

If you need to build ApplicationContexta hierarchy (contained parentand childmore contextual relationships), or if you prefer to use "fluent" builder API, then you can use SpringApplicationBuilder.

SpringApplicationBuilderIt allows you to link together multiple method calls, and allows you to create a hierarchy includes parent and child class method, as shown in the following example:

new SpringApplicationBuilder()
        .sources(Parent.class) .child(Application.class) .bannerMode(Banner.Mode.OFF) .run(args);
Creating a ApplicationContext time hierarchy, with some restrictions, for example, Web components must be included in the sub-context, and are used in the parent and child in the same context Environment , see SpringApplicationBuilder Javadoc for more information.

23.5 Application events and listeners

In addition to the usual Spring framework events, such as ContextRefreshedEvent outside, SpringApplicationbut also send some additional application events.

Creating ApplicationContext before actually triggered the events and therefore can not be registered as a listener @Bean . You can use the SpringApplication.addListeners(...) method or SpringApplicationBuilder.listeners(...) registering their methods. If you want these listeners registered automatically, regardless of how the application is created, you can add a META-INF/spring.factories file to your project, and by using org.springframework.context.ApplicationListener to refer to your listeners key, as in this example:

org.springframework.context.ApplicationListener=com.example.project.MyListener

Application event sent in the following order:

  1. A ApplicationStartingEventis sent at the beginning of the run, but before any treatment, in addition to registering listeners and initializers.
  2. Before creating a context, as Environmentwhen used in this context, it will send a ApplicationEnvironmentPreparedEvent.
  3. A ApplicationPreparedEventis sent before the refresh start, but after loading the bean definitions.
  4. After sending a call to the context ApplicationStartedEvent, but before calling any application and command-line program.
  5. After calling any applications and command line to run the program, will send a ApplicationReadyEvent, it indicates that the application is ready to service requests.
  6. Exception occurs when you start, then send ApplicationFailedEvent.
You usually do not need to use an application event, but know that their presence is very convenient. In the interior, Spring Boot using the event to handle a variety of tasks.

Use the Spring Framework event publishing mechanism to send an application event, part of the mechanism to ensure that the child be released in the environment to the listeners of the event will be released to the listener in any ancestor context. So, if your application uses a SpringApplicationhierarchy of instances, the listener may receive multiple instances of the application of the same type of event.

To make your listener distinguish the context of events and derived contexts event, it should request that their application context is injected, and then injected into context by comparing the event context, can be achieved ApplicationContextAwareor if the listener bean, by used @Autowiredto inject context.

23.6 Web environment

SpringApplicationTrying to create the right for your ApplicationContexttype, is used to determine WebEnvironmentTypethe algorithm is quite simple:

  • If there is Spring MVC is used AnnotationConfigServletWebServerApplicationContext.
  • If there is no Spring MVC, Spring WebFlux exist, then use a AnnotationConfigReactiveWebServerApplicationContext.
  • Otherwise, AnnotationConfigApplicationContextit is used.

This means that if you use Spring MVC and Spring WebFlux from the new WebClient, Spring MVC will be used by default in the same application, you can call setWebApplicationType(WebApplicationType)it easy to cover it.

You can also call setApplicationContextClass(…)complete control over the use of ApplicationContexttype.

In JUnit tests SpringApplication , it is often need to call setWebApplicationType(WebApplicationType.NONE) .

23.7 to access the application parameters

If you need to access pass to SpringApplication.run(…)the application parameter, you can inject a org.springframework.boot.ApplicationArgumentsthe bean, ApplicationArgumentsthe interface provides primitive String[]parameters and an analysis optionand non-optionaccess parameters, in the following example:

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"); List<String> files = args.getNonOptionArgs(); // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] } }
Spring Boot will be in Spring Environment registered one CommandLinePropertySource , which allows you to use @Value annotations injecting a single application parameters.

23.8 Use ApplicationRunner or CommandLineRunner

If you need to SpringApplicationrun some specific code after the start, you can achieve ApplicationRunneror CommandLineRunnerinterfaces, both interfaces work in the same way, and provide a separate RUN 方法, the SpringApplication.run(…)call before completion.

CommandLineRunnerInterface provides access to an application parameter as a simple array of strings, ApplicationRunnerusing previously discussed ApplicationArgumentsinterfaces. The following example illustrates a use of runthe method CommandLineRunner:

import org.springframework.boot.*; 
import org.springframework.stereotype.*;

@Component
public class MyBean implements CommandLineRunner { public void run(String... args) { // Do something... } }

If you define more than one CommandLineRunneror ApplicationRunnerbean, you must call them in a specific order, then you may additionally implement org.springframework.core.Orderedinterfaces or org.springframework.core.annotation.Orderannotations.

23.9 application quits

Each SpringApplicationare registered with a JVM shutdown hook to ensure that ApplicationContextgracefully closed on exit. Spring can use all the standard lifecycle callback function (such as DisposableBeaninterface or @PreDestroynotes).

In addition, when SpringApplication.exit()the time is called if you want to return a specific exit code of the bean can implement org.springframework.boot.ExitCodeGeneratorthe interface. This code is then passed to the exit System.exit(), so as to be used as the status code returned, as shown in the following example:

@SpringBootApplication
public class ExitCodeApplication { @Bean public ExitCodeGenerator exitCodeGenerator() { return () -> 42; } public static void main(String[] args) { System.exit(SpringApplication .exit(SpringApplication.run(ExitCodeApplication.class, args))); } }

Further, ExitCodeGeneratorthe interface may be implemented by abnormal, we encountered when such an exception, Spring Boot implemented returned by getExitCode()the exit code provided methods.

23.10 management functions

By specifying spring.application.admin.enabledenable property-related properties for an application admin, which will be the platform MBeanServeropen on SpringApplicationAdminMXBean , you can use this feature to remotely manage your Spring Boot applications, this feature can also be used to achieve any service wrapper.

If you want to know which applications are running HTTP port, use the local.server.port key to acquire the property.
When you enable this feature to note because MBean it discloses a method to close the application.
 

Guess you like

Origin www.cnblogs.com/duanxz/p/11233572.html