In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to configure Spring Application". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to configure Spring Application.
I. Overview
At present, Spring Boot has developed to 2.3.4.RELEASE, and its benefits are overwhelming online, so I won't repeat it here. To get to the point, we have encountered a lot of pitfalls when upgrading from Spring Boot1.x to 2.3.4 step by step. It is very important to understand the features of the new version, which can help us avoid a lot of unnecessary trouble.
Because I have also been working on component development based on the Spring Boot technology stack, and recently prepared for partial refactoring of the basic components, by the way, I will review and summarize the features of the current version from scratch. This review only introduces some features of the current version, and does not describe the features. If you are interested, you can @ me, and later I will conduct a detailed analysis according to a certain piece. Friends you like can follow and have a look. I hope it will be helpful to you.
2. Application1 from scratch, failed to start the application (Startup Failure)
If the application fails to start, Spring Boot will help us print the information about why the application failed, such as the following when I start the application on port 6080 for the second time
* * APPLICATION FAILED TO START**Description:Embedded servlet container failed to start. Port 6080 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.
It's a lot of happiness to have such a friendly hint, and Spring Boot also provides us with more extension interface FailureAnalyzer and a responsive abstract class AbstractFailureAnalyzer. If we do not meet his default startup exception information, we can do some customized development through FailureAnalyzer (such as printing a stack when an exception occurs). The extension of FailureAnalyzer uses SPI, so when we use it, we need to create a META-INF/spring.factories in the application to declare our implementation, the following is a small demo.
/ * * first create our own class, and we can intercept exceptions according to our own needs. Here I intercept port occupancy exception PortInUseException * @ ClassName LearningFailureAnalyzer * @ Author QIANGLU * @ Date 9:10 on 2020-9-23 * @ Version 1.0 * / public class LearningFailureAnalyzer extends AbstractFailureAnalyzer {private static final Logger LOGGER = LoggerFactory.getLogger (LearningFailureAnalyzer.class) @ Override protected FailureAnalysis analyze (Throwable rootFailure, PortInUseException cause) {LOGGER.error ("I have an exception, wow card"); return new FailureAnalysis ("Port:" + cause.getPort () + "occupied", cause.getMessage (), rootFailure) The second step is to create a META-INF/spring.factories. The following org.springframework.boot.diagnostics.FailureAnalyzer=\ com.qianglu.chapter1.failure.LearningFailureAnalyzer / / the third cloth starts our application twice, and we will find that The printed information is what we need * * APPLICATION FAILED TO START**Description: Port: 6080 occupied Action:Port 6080 is already in use
There are actually a lot of scenes available for this thing. Let's think about whether it is any inspiration.
2. Delayed initialization (Lazy Initialization)
When Spring Boot first came out, it was complained that it was slow to start and load, but now lazy loading is coming. Allow your application to start lazy loading, and your beans does not need to be created at the start of the project and when to use it. This can save you a lot of startup time, but there are advantages and disadvantages. Lazy loading will cause a lot of web-related bean to be delayed in web applications, and will not be initialized until there is a request, so you must pay attention to it when using it, otherwise there will be abnormalities that make you confused.
And the official also said that if you have delayed initialization, some problems may also be delayed to be discovered. For example, some of our previous configurations are mismatched, and we often report that XXXbean cannot be found at startup. Hey hey, now can not, the same start-up success, only when you use the time to give you off the chain, ask you are afraid of it.
In addition, the official prompt to delay initialization will cause the initial jvm memory performance to be relatively small, but you should pay attention to configuring enough memory for future object creation (I don't think this is a problem in general applications, and you don't need to pay too much attention).
Let's take a look at two configurations:
Use SpringApplication to call the setLazyInitialization method to set
Use configuration spring.main.lazy-initialization=true
If you set deferred initialization and have some special classes that want to initialize, you can configure @ Lazy (false) to turn off its lazy loading.
3. Configure Banner
To tell you the truth, I have never known the use of this thing. in the past, we all configured a big Buddha to ensure safety, which was more entertaining than reality, of course, there may be no point where GET arrived.
The configuration method is also very simple, which is to assign a banner.txt to your classpath and specify the location of the file through the spring.banner.location configuration. Of course, there are a lot of attributes, such as coding, gif, version and so on, I actually don't bother to say, I'm not interested.
# 4. Configure your SpringApplication
We generally start the class is to directly call SpringApplication.run on the line. But if you think it's too simple and boring, there are actually a lot of interesting properties in SpringApplication.run that you can take a look at, such as I turn off banner.
Public static void main (String [] args) {SpringApplication app = new SpringApplication (MySpringConfiguration.class); app.setBannerMode (Banner.Mode.OFF); app.run (args);}
Of course, there are many configuration properties, and you can also use application.yml to configure the properties of SpringApplication.
5. Stream build API (Fluent Builder API)
The official SpringApplicationBuilder class is provided to help you create multi-level ApplicationContext using streaming build. SpringApplicationBuilder can help us build a hierarchical relationship, which is equal to SpringApplication.run in this way
New SpringApplicationBuilder () .sources (Parent.class) .child (Application.class) .bannerMode (Banner.Mode.OFF) .run (args); 6. Application availability (Application Availability)
What we are talking about here is actually Liveness and Readiness of K8s, which have become the core of Spring Boot.
In a nutshell, Liveness and Readiness represent all aspects of application state in k8s.
Liveness status to view the internal situation can be understood as health check. If Liveness fails, it means that the application is in a failed state and cannot be recovered at this time. Restart in this case.
Readiness status is used to tell the application whether it is ready to accept client requests, and if Readiness is not ready, K8s cannot route traffic.
We can use code to monitor the Readiness status and do the processing we need.
Componentpublic class ReadinessStateExporter {@ EventListener public void onStateChange (AvailabilityChangeEvent event) {switch (event.getState ()) {case ACCEPTING_TRAFFIC: / / xxxxx break; case REFUSING_TRAFFIC: / / xxxxxx break;}
We can also change this state to perform dynamic degradation and isolation when the application fails and cannot be recovered. This is really cool. I have the opportunity to suggest you to give it a try.
@ Componentpublic class LocalCacheVerifier {private final ApplicationEventPublisher eventPublisher; public LocalCacheVerifier (ApplicationEventPublisher eventPublisher) {this.eventPublisher = eventPublisher;} public void checkLocalCache () {try {/ /...} catch (CacheCompletelyBrokenException ex) {AvailabilityChangeEvent.publish (this.eventPublisher, ex, LivenessState.BROKEN);}} 7, events and Monitoring (Application Events and Listeners)
Spring Boot's event notification mechanism is simply a decoupling artifact, including the distributed remote notification mechanism used by Spring Cloud. In fact, this is also the core, which adds a layer of middleware for message delivery.
Some events cannot be declared using @ Bean because they are actually triggered before the ApplicationContext is created. It is best to use SpringApplication.addListeners (…) And SpringApplicationBuilder.listeners (…) To register the listener.
But if you really can't grasp the timing of these loads, then a universal way is to configure the SPI extension, configure it directly in META-INF/spring.factories, and add your listener, such as org.springframework.context.ApplicationListener=com.example.project.MyListener
The official description of the order of events that will be sent at startup:
1. ApplicationStartingEvent sends events at the beginning of the run
2. ApplicationEnvironmentPreparedEvent sends an event when Environment is used in context
3. ApplicationContextInitializedEvent sends an event when ApplicationContext is ready and ApplicationContextInitializers has been called before all bean definitions
4. Send events before ApplicationPreparedEvent refreshes the configuration and after the definition of bean is loaded
5. After ApplicationStartedEvent refreshes the context, before executing the implementation of CommandLineRunner
6. AvailabilityChangeEvent sends LivenessState.CORRECT surface application is active
7. ApplicationReadyEvent is sent after executing the CommandLineRunner interface
8. After AvailabilityChangeEvent sends ReadinessState.ACCEPTING_TRAFFIC, the application can access the traffic.
9. ApplicationFailedEvent sends the failed event of application startup
The above is only the events of SpringApplicationEvent, generally we do not need to operate on these, with you need to know its existence, lest problems do not know how to find, in fact, other people's Spring Boot has been sent to you.
8. Web attribute
Generally speaking, using SpringApplication will create the correct ApplicationContext type for us. The way to determine the WebApplicationType, that is, the application type, is actually very simple:
Use AnnotationConfigServletWebServerApplicationContext if Spring MVC exists
If Spring MVC does not exist, but Spring WebFlux exists, use AnnotationConfigReactiveWebServerApplicationContext
If there is none, then use AnnotationConfigApplicationContext.
If you use both Spring MVC and Spring WebFlux WebClient,Spring MVC, it is used by default, unless you set SpringApplication.setWebApplicationType (WebApplicationType) to force the change.
9. Access application parameters (Accessing Application Arguments)
If you want to visit SpringApplication.run (…) You can actually inject an org.springframework.boot.ApplicationArguments object. The API ApplicationArguments provides access to the original String [] parameters, as well as parsed options and non-option parameters, and go to demo:
Import org.springframework.boot.*;import org.springframework.beans.factory.annotation.*;import org.springframework.stereotype.*;@Componentpublic class MyBean {@ Autowired public MyBean (ApplicationArguments args) {boolean debug= args.containsOption ("debug"); List files= args.getNonOptionArgs (); / / if run with "--debug logfile.txt" debug=true, files= ["logfile.txt"]}}
The environment variable in Spring Boot also registers a CommandLinePropertySource, and we can use @ Value to get an environment variable.
10. Use ApplicationRunner or CommandLineRunner
These two goods are also things we often use. If you need to load something at the start of the project, they are simply artifacts. Both interfaces provide a run method, which will be used in SpringApplication.run (…). Called before the execution is completed. These two interfaces are suitable for handling something before the application receives the request.
Give an example of using it.
Import org.springframework.boot.*;import org.springframework.stereotype.*;@Componentpublic class MyBean implements CommandLineRunner {public void run (String... Args) {/ / Do something... }}
If we define multiple CommandLineRunner or ApplicationRunner implementations and sometimes need to have a sequence of execution, we can use the org.springframework.core.annotation.Order annotation to define it.
11. Application exit (Application Exit)
Each SpringApplication registers a shutdown hook like JVM to ensure a normal exit. Make sure that callbacks such as the @ PreDestroy annotation and the DisposableBean interface are executed.
In addition, if you want to return some special exit code when using SpringApplication.exit (), you can implement the org.springframework.boot.ExitCodeGenerator interface and pass it to System.exit () for return. Such as:
@ SpringBootApplicationpublic class ExitCodeApplication {@ Bean public ExitCodeGenerator exitCodeGenerator () {return ()-> 42;} public static void main (String [] args) {System.exit (SpringApplication.exit (SpringApplication.run (ExitCodeApplication.class, args));}}
The ExitCodeGenerator interface can be implemented through exceptions. When such an exception is encountered, Spring Boot returns the exit code provided by the implemented getExitCode () method
12. Administrator function (Admin Features)
We can use the spring.application.admin.enabled property to turn on the administrator function. If you turn it on, you will expose all your own SpringApplicationAdminMXBean to MBeanServer, and you can also use this feature to remotely operate your application. But if you want to understand the security issues, don't mess around if you don't have to.
Thank you for your reading, the above is the content of "how to configure Spring Application", after the study of this article, I believe you have a deeper understanding of how to configure Spring Application, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.