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 FailureAnalyzers
will have the opportunity to provide specific error messages and specific actions to resolve the problem. For example, if you are in port 8080
start 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.ConditionEvaluationReportLoggingListener
enable the debug attribute or enable DEBUG logging .
For example, if you're using java -jar
to run your application, you can enable the debug
following properties:
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
23.2 Custom Banner
Banner printing at startup can add banner.txt
to your class path or set file spring.banner.location
attributes 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.jpg
or banner.png
image files to your class path or set spring.banner.image.location
properties. The image is converted into ASCII art representation, and any text printed on the title.
In your banner.txt
file, you can use any of the following placeholders:
Table 23.1. Banner variable
variable |
description |
${application.version} |
In the MANIFEST.MF version number of the application declared, for example, Implementation-Version:1.0 are printed as1.0 |
${application.formatted-version} |
The version number of the application, as MANIFEST.MF declared 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 v prefix), e.g.(v2.0.5.RELEASE) |
${Ansi.NAME} or${AnsiColor.NAME} |
NAME Is 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:MyApp are 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-mode
property 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 SpringApplication
the 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.properties
configuration 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 ApplicationContext
a hierarchy (contained parent
and child
more contextual relationships), or if you prefer to use "fluent" builder API, then you can use SpringApplicationBuilder
.
SpringApplicationBuilder
It 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, SpringApplication
but 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:
- A
ApplicationStartingEvent
is sent at the beginning of the run, but before any treatment, in addition to registering listeners and initializers.
- Before creating a context, as
Environment
when used in this context, it will send a ApplicationEnvironmentPreparedEvent
.
- A
ApplicationPreparedEvent
is sent before the refresh start, but after loading the bean definitions.
- After sending a call to the context
ApplicationStartedEvent
, but before calling any application and command-line program.
- 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.
- 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 SpringApplication
hierarchy 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 ApplicationContextAware
or if the listener bean, by used @Autowired
to inject context.
23.6 Web environment
SpringApplication
Trying to create the right for your ApplicationContext
type, is used to determine WebEnvironmentType
the 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,
AnnotationConfigApplicationContext
it 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 ApplicationContext
type.
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.ApplicationArguments
the bean, ApplicationArguments
the interface provides primitive String[]
parameters and an analysis option
and non-option
access 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();
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 SpringApplication
run some specific code after the start, you can achieve ApplicationRunner
or CommandLineRunner
interfaces, both interfaces work in the same way, and provide a separate RUN 方法
, the SpringApplication.run(…)
call before completion.
CommandLineRunner
Interface provides access to an application parameter as a simple array of strings, ApplicationRunner
using previously discussed ApplicationArguments
interfaces. The following example illustrates a use of run
the method CommandLineRunner
:
import org.springframework.boot.*;
import org.springframework.stereotype.*;
@Component
public class MyBean implements CommandLineRunner { public void run(String... args) {
If you define more than one CommandLineRunner
or ApplicationRunner
bean, you must call them in a specific order, then you may additionally implement org.springframework.core.Ordered
interfaces or org.springframework.core.annotation.Order
annotations.
23.9 application quits
Each SpringApplication
are registered with a JVM shutdown hook to ensure that ApplicationContext
gracefully closed on exit. Spring can use all the standard lifecycle callback function (such as DisposableBean
interface or @PreDestroy
notes).
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.ExitCodeGenerator
the 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, ExitCodeGenerator
the 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.enabled
enable property-related properties for an application admin, which will be the platform MBeanServer
open 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.