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, FailureAnalyzers
reports an error message.
4.1.2. Lazy initialization (lazy loading)
SpringApplication
Allowable 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:
SpringApplicationBuilder
start up
org.springframework.boot.builder.SpringApplicationBuilder#lazyInitialization
SpringApplication
Designation
org.springframework.boot.SpringApplication#setLazyInitialization
- Configuration Properties
spring.main.lazy-initialization=true
Use lazy initialization of bean, you can use @Lazy
annotations.
4.1.3. Custom Banner
The banner.txt
or image files ( banner.gif
, banner.jpg
or 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.txt
internal documents, you can use any of the following placeholders, refer to:
Variable | Description
--- | ---
${application.version}
| version number of your application, as MANIFEST.MF
the 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#setBanner
generated programmatically Banner
.
Attribute spring.main.banner-mode
specifies the print Banner way.
Banner printing a single instance of the bean id is: springBootBanner
.
4.1.4. Custom SpringApplication
Passed to the SpringApplication
constructor parameters are Spring bean configuration source. In most cases, these are for the @Configuration
reference to the class, but they can also be a reference to the XML configuration or should scan package.
You can also use application.properties
to 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 ApplicationContext
some 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 ApplicationContext
before the trigger, so you can not be registered as a listener @Bean
to 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.factories
add files to the project, and use the org.springframework.context.ApplicationListener
key 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
:
ApplicationStartingEvent
When transmitting the operation start, but (except for the initialization procedure and listener registration) transmitted prior to any treatment.
listeners.starting();
ApplicationEnvironmentPreparedEvent
Environment when the context is sent to the known use, the context is created but before.
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
ApplicationContextInitializedEvent
In theApplicationContext
ready and has been calledApplicationContextInitializers
after, but not loaded before any bean definitions, sent.
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
listeners.contextPrepared(context);
ApplicationPreparedEvent
But sent after loading the bean definitions before refreshing start.
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
listeners.contextLoaded(context);
ApplicationStartedEvent
After the context has been refreshed, howeverapplication runners
, andcommand-line runners
the former is called, sent.
listeners.started(context);
ApplicationReadyEvent
Inapplication runners
andcommand-line runners
sent after being called. It indicates that the application is ready to process requests.
listeners.running(context);
ApplicationFailedEvent
When start sending abnormal.
handleRunFailure(context, ex, exceptionReporters, listeners);
Additional events, in ApplicationPreparedEvent
and ApplicationStartedEvent
between the transmission:
ContextRefreshedEvent
InApplicationContext
sending refresh.WebServerInitializedEvent
After sending WebServer ready.ServletWebServerInitializedEvent
AndReactiveWebServerInitializedEvent
are 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 SpringApplication
a 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 ApplicationContextAware
by injecting the context, or, if the listener is a bean, the use @Autowired
injection context.
4.1.7。Web Environment
SpringApplication
Trying to create the correct type ApplicationContext
. Determine WebApplicationType
the algorithm is very simple:
- If there is
Spring MVC
, useAnnotationConfigServletWebServerApplicationContext
- If there is no
Spring MVC
and thereSpring 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 MVC
and Spring WebFlux
new features, it will be used by default Spring MVC
. By calling org.springframework.boot.SpringApplication#setWebApplicationType
easily cover it. You can also call org.springframework.boot.SpringApplication#setApplicationContextClass
directly ApplicationContext
.
4.1.8. Access application parameters
If you need access pass 给SpringApplication.run(...)
application parameters, you can inject org.springframework.boot.ApplicationArgumentsBean
. ApplicationArguments
Interface 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 @Value
annotation injecting a single application parameters.
4.1.9. Use ApplicationRunner
orCommandLineRunner
If you start SpringApplication
you need to run some specific code, it is possible to implement ApplicationRunner
or CommandLineRunner
interface. 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.
ApplicationRunner
And CommandLineRunner
the 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.Ordered
interfaces or org.springframework.core.annotation.Order
annotations.
4.1.10。Application Exit
Each SpringApplication
have a shutdown hook to the JVM registered, in order to ensure ApplicationContext
the normal close on exit. You can use all the standard Spring lifecycle callbacks (for example, DisposableBean
an interface or @PreDestroy
annotation).
If you want to SpringApplication.exit()
return a specific exit code is called, you can implement org.springframework.boot.ExitCodeGenerator
the interface. This code is then passed to the exit System.exit()
, so as to be returned as the status code.
Further, Exception
to achieve ExitCodeGenerator
the 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.port
acquiring property.