20191110 Spring Boot official document learning (4.1)

4. Spring Boot function

4.1. Spring Applications

Convenient way to start:

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

SpingBoot default logging levels are INFO.

4.1.1. Startup failed

When you start failure, FailureAnalyzersreports an error message.

4.1.2. Lazy initialization (lazy loading)

SpringApplicationAllowable delay initialize the application. When you enable lazy initialization, bean will be created as needed, rather than creating bean during application startup.

The following ways to start the lazy initialization:

  1. SpringApplicationBuilderstart up
org.springframework.boot.builder.SpringApplicationBuilder#lazyInitialization
  1. SpringApplicationDesignation
org.springframework.boot.SpringApplication#setLazyInitialization
  1. Configuration Properties
spring.main.lazy-initialization=true

Use lazy initialization of bean, you can use @Lazyannotations.

4.1.3. Custom Banner

The banner.txtor image files ( banner.gif, banner.jpgor banner.png) in the class path, or by setting the property specified path spring.banner.location(images spring.banner.image.location). The image will be converted toASCII

In banner.txtinternal documents, you can use any of the following placeholders, refer to:
Variable | Description
--- | ---
${application.version}| version number of your application, as MANIFEST.MFthe medium. For example, Implementation-Version: 1.0 1.0 Print.
${application.formatted-version}| Your application version number, as in the MANIFEST.MF, and a format (in brackets, and with the prefix v). For example (v1.0).
${spring-boot.version}| Spring Boot version you are using. For example 2.2.0.RELEASE.
${spring-boot.formatted-version}| Spring Boot version you are using, the format for display (with brackets, and with the prefix v). For example (v2.2.0.RELEASE).
${Ansi.NAME}(Or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME}) | NAME is the name of ANSI escape code. For more information, see AnsiPropertySource.
${application.title}| Title of your application, as described in the MANIFEST.MF. For example Implementation-Title: MyApp printed as MyApp.

Use org.springframework.boot.SpringApplication#setBannergenerated programmatically Banner.

Attribute spring.main.banner-modespecifies the print Banner way.

Banner printing a single instance of the bean id is: springBootBanner.

4.1.4. Custom SpringApplication

Passed to the SpringApplicationconstructor parameters are Spring bean configuration source. In most cases, these are for the @Configurationreference to the class, but they can also be a reference to the XML configuration or should scan package.

You can also use application.propertiesto configure the file. See more information about SpringApplication.

For a complete list of configuration options, see org.springframework.boot.SpringApplication.

4.1.5. Streaming Builder API

org.springframework.boot.builder.SpringApplicationBuilder

Example:

new SpringApplicationBuilder(SpringbootApplication.class).profiles("server")
        .properties("transport=local").run(args);

Create ApplicationContextsome restrictions hierarchy. Example, Web components must be included in the child context and the parent and child use the same context Environment.

4.1.6. Application events and listeners

Some events are actually created ApplicationContextbefore the trigger, so you can not be registered as a listener @Beanto listen for events. You can use the SpringApplication.addListeners(...)method or SpringApplicationBuilder.listeners(...)registering their methods.

If you want these listeners registered automatically, regardless of the way how to create an application, you can META-INF/spring.factoriesadd files to the project, and use the org.springframework.context.ApplicationListenerkey references your listeners, as in the following example:

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

Analysis method for starting
org.springframework.boot.SpringApplication#run(java.lang.String...)
the application sent in the following order in the event your application is running, these events are tied to SpringApplication上the SpringApplicationEvents:

  1. ApplicationStartingEventWhen transmitting the operation start, but (except for the initialization procedure and listener registration) transmitted prior to any treatment.
listeners.starting();
  1. ApplicationEnvironmentPreparedEventEnvironment when the context is sent to the known use, the context is created but before.
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
  1. ApplicationContextInitializedEventIn the ApplicationContextready and has been called ApplicationContextInitializersafter, but not loaded before any bean definitions, sent.
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
listeners.contextPrepared(context);
  1. ApplicationPreparedEventBut sent after loading the bean definitions before refreshing start.
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
listeners.contextLoaded(context);
  1. ApplicationStartedEventAfter the context has been refreshed, however application runners, and command-line runnersthe former is called, sent.
listeners.started(context);
  1. ApplicationReadyEventIn application runnersand command-line runnerssent after being called. It indicates that the application is ready to process requests.
listeners.running(context);
  1. ApplicationFailedEventWhen start sending abnormal.
handleRunFailure(context, ex, exceptionReporters, listeners);

Additional events, in ApplicationPreparedEventand ApplicationStartedEventbetween the transmission:

  1. ContextRefreshedEventIn ApplicationContextsending refresh.
  2. WebServerInitializedEventAfter sending WebServer ready. ServletWebServerInitializedEventAnd ReactiveWebServerInitializedEventare responsive servlet servlet and variants.

Application events are sent by using the Spring Framework event publishing mechanism. This mechanism ensures that part of the event posted in the child context to the listeners will be released to the listener in any ancestor context. So, if your application uses SpringApplicationa hierarchy instance, the listener may receive multiple instances of the application of the same type of event.

To make your listener can distinguish between events and future context of the events that context, it should request inject its application context, and then injected into the context of the comparison with the context of the event. It can be achieved ApplicationContextAwareby injecting the context, or, if the listener is a bean, the use @Autowiredinjection context.

4.1.7。Web Environment

SpringApplicationTrying to create the correct type ApplicationContext. Determine WebApplicationTypethe algorithm is very simple:

  • If there is Spring MVC, useAnnotationConfigServletWebServerApplicationContext
  • If there is no Spring MVCand there Spring WebFlux, useAnnotationConfigReactiveWebServerApplicationContext
  • Otherwise,AnnotationConfigApplicationContext

Reference Source:

org.springframework.boot.SpringApplication#run(java.lang.String...)
    context = createApplicationContext();


org.springframework.boot.SpringApplication#SpringApplication(org.springframework.core.io.ResourceLoader, java.lang.Class<?>...)
    this.webApplicationType = WebApplicationType.deduceFromClasspath();

Used in the same applications Spring MVCand Spring WebFluxnew features, it will be used by default Spring MVC. By calling org.springframework.boot.SpringApplication#setWebApplicationTypeeasily cover it. You can also call org.springframework.boot.SpringApplication#setApplicationContextClassdirectly ApplicationContext.

4.1.8. Access application parameters

If you need access pass 给SpringApplication.run(...)application parameters, you can inject org.springframework.boot.ApplicationArgumentsBean. ApplicationArgumentsInterface provides the original String[], as well as the following exemplary parameters resolved access option and non-option parameters is as follows:

@Component
public class MyBean {
    @Autowired
    public MyBean(ApplicationArguments args) {
        boolean debug = args.containsOption("debug");
        List<String> nonOptionArgs = args.getNonOptionArgs();
        // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
    }
}

Spring Boot also registered an Environment to the Spring CommandLinePropertySource. This way, you can also use the @Valueannotation injecting a single application parameters.

4.1.9. Use ApplicationRunnerorCommandLineRunner

If you start SpringApplicationyou need to run some specific code, it is possible to implement ApplicationRunneror CommandLineRunnerinterface. Both interfaces work in the same way, and provide a single run method in SpringApplication.run (...) is invoked before completion.

Reference Source:

org.springframework.boot.SpringApplication#run(java.lang.String...)
    callRunners(context, applicationArguments);

Not the asynchronous call when Runner, but are executed between ApplicationStartedEvent events and ApplicationReadyEvent.

ApplicationRunnerAnd CommandLineRunnerthe interface differs from that of the different parameters, the former ApplicationArguments, the latter String....

If there are multiple Runner, it is necessary to specify the order of execution may be implemented org.springframework.core.Orderedinterfaces or org.springframework.core.annotation.Orderannotations.

4.1.10。Application Exit

Each SpringApplicationhave a shutdown hook to the JVM registered, in order to ensure ApplicationContextthe normal close on exit. You can use all the standard Spring lifecycle callbacks (for example, DisposableBeanan interface or @PreDestroyannotation).

If you want to SpringApplication.exit()return a specific exit code is called, you can implement org.springframework.boot.ExitCodeGeneratorthe interface. This code is then passed to the exit System.exit(), so as to be returned as the status code.

Further, Exceptionto achieve ExitCodeGeneratorthe interface. When an exception is thrown, Spring Boot implemented returned by getExitCode()the exit code provided methods.

Example:

@SpringBootApplication
public class SpringbootApplication {

    @Bean
    public ExitCodeGenerator exitCodeGenerator() {
        return () -> 42;
    }

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

}

Direct stop the virtual machine can not return a specific exit code.

4.1.11. Administrator functions

By specifying spring.application.admin.enabled, you can enable the administrator functions related to the application properties. It will open on the platform MBeanServer SpringApplicationAdminMXBean. You can use this feature to remotely manage Spring Boot application. This feature is implemented for any service package also may be useful.

If you want to know the application on which to run the HTTP port, please key local.server.portacquiring property.

Guess you like

Origin www.cnblogs.com/huangwenjie/p/11831512.html