Springboot Start too slow optimization

Source: Internet
Author: User

Demand Origin : Someone in the "springboot" public question: Springboot start slow problem when there is a share, thank you. The fans ' question is still to be answered seriously.

Let's look at the outline of this section first:

(1) Problems caused by automatic component scanning (@SpringBootApplication);
(2) How to avoid the problem caused by automatic component scanning (do not use @ springbootapplication);
(3) Problems caused-unable to scan components;
(4) The Red House has only one dream, naught;
(5) Debug debug,bug bug more healthy;
(6) Analysis of positive matches and negative matches;
(7) Optimize the configuration information again;
(8) Summary

Next we'll explore each of these issues.

(1) Problems caused by automatic component scanning (@SpringBootApplication);

We introduced it in the first blog, and by default we use @springbootapplication annotations to automatically get the app's configuration information, but there are some side effects. With this annotation, automatic configuration (auto-configuration) and component scanning (component scanning) are triggered, which is followed by the use of @configuration, @ The Enableautoconfiguration and @componentscan three annotations function the same. This will bring convenience to the development as well as some of the following effects:

(a) can lead to longer project start-up time (reason: loading the components we don't need to use, wasting CPU resources and memory resources). When launching a large application, or will do a lot of integration testing to launch the application, the impact will be particularly noticeable.

(b) Some unnecessary instances (beans) are loaded.

(c) Increases CPU consumption and memory usage.

(2) How to avoid the problem caused by automatic component scanning (do not use @ springbootapplication);

In the spirit of the problem is to solve the mentality, against the above problems, how can we solve it? Obviously, since @springbootapplication loads some unnecessary configuration, do we think we can load our own specified configuration? Our train of thought does not use @springbootapplication, and does not use @componentscan annotations (this note automatically scans the classes that we annotated @controller, @Service annotations, loaded into the spring IOC container), We then use @configuration and @enableautoconfiguration to configure the startup class with the following code:

Package com.kfit.spring_boot_performance;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import Org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import Com.kfit.spring_boot_performance.controller.HelloController;

/**

* @author Angel--Guardian Angel

* @version v.0.1

* @date March 11, 2017

*/

Remove @SpringBootApplication and @ComponentScan, replace with @EnableAutoConfiguration

@Configuration

@EnableAutoConfiguration

Public class App {

Public Static void Main (string[] args) {

Springapplication. Run (App.class, args);

}

}

(3) Problems caused-unable to scan components;

We were just about to improve our code and we found the problem. After launch, access to our written access page/index, error: There is an unexpected error (Type=not Found, status=404).

What is the cause of this? Remember that we just introduced the @componentscan annotation, enable this annotation spring to be able to do automatic component scanning, otherwise we can not scan to the component class we write. So what's the problem? The solution to the problem is to explicitly configure it.

The injected code is as follows (suppose we write the class is Hellocontroller, where the blogger writes directly in the App.java startup class for injection):

@Bean

Public Hellocontroller Hellocontroller () {

return New Hellocontroller ();

}

Explicitly configured in the code above with @Bean annotations to be scanned by Spring.

After the reboot, we will be able to access the/index page normally.

There will be people here who will say, "That's not going to increase the amount of code we have." I can only say: you have to load fast, but also do not code, Bo Lord really do not know how to do. Everything has its pros and cons.

(4) A dream in the Red mansion, naught

Some people do not believe that this can really start faster, and then the code to test. Haha, the betrayed, or the same as the start of the snail as slow. Then why is that so? Why we study the half-day, the end is: The Red Mansion only a dream, naught.

Smart readers will notice that we mention that the role of @SpringBootApplication annotations is equivalent to the @enableautoconfiguration annotation, which means that it can also lead to the above problems. To avoid these problems, we need to know what our component list is.

(5) Debug Debug,bug bug More healthy

As we said above, our question is how do we know what our component list is? At this time, Debug is a grand debut, applause welcome Mr. Debug to play.

May I ask Mr. Debug: What is your acceptance speech at this moment?

Mr. Debug: After a slow life, I finally found my value. Here I would like to thank CCTV, thanks to MTV, thanks to Coca-Cola, thanks very much coke, thank jdb, thank Wanglaoji, thank the organizer Springboot, let me have the opportunity to meet with you on this stage. Thank you, I will not let everyone down.

Well, the nonsense is not much to say, we first see how to use the debug?

First case: Using Spring-boot:run startup mode

In this case, the complete running code is:

Spring-boot:run-ddebug

Second case: Using the Run As--java application boot mode

In this case, configure the VM parameters to do the following:

"Right"--"run as"--"Run configurations ..."--"Select arguments"--"VM arguments" added: "-ddebug".

At this point in the boot, we can see the console print out some of the log information we do not normally see.

=========================
Auto-configuration Report
=========================
Positive matches:
-----------------

Dispatcherservletautoconfiguration matched
-@ConditionalOnClass found required class ' Org.springframework.web.servlet.DispatcherServlet ' (onclasscondition)
-@ConditionalOnWebApplication (required) found Standardservletenvironment (onwebapplicationcondition)
The remaining print information is omitted here ...

(6) Analysis of positive matches and negative matches;

In the printed information, we need to understand some of the knowledge here:

(a) Positive match: The configuration item that matches to the corresponding class is exhausted.
(b) Negative match: The reason why a configuration item is not included.

Now give an example of datasourceautoconfiguration:

(a) @ConditionalOnClass indicate that the corresponding class exists in the Classpath directory before parsing the corresponding configuration file. For datasourceautoconfiguration, it means: only Javax.sql.DataSource and Org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseTy When a PE class is present, the corresponding database resource is configured.
(b) @ConditionalOnMissingClass indicates that the corresponding class could not be found under the Classpath directory.
(c) Onclasscondition is used to indicate the type of match (postive or negative).
Onclasscondition is the most common browsing detection condition, except that Spring boot also uses other detection conditions, such as: Onbeancondition to detect the existence or absence of a specified bean instance, The onpropertycondition is used to check for the existence of a specified property and so on.
Conforming to negative match represents some configuration classes (such as xxxconfiguration), although they exist in the Classpath directory, but other classes that are dependent on the annotations that decorate them do not exist.

(7) Optimize configuration information again

Based on the above theoretical knowledge, we only need to introduce these components explicitly at startup, copying the information listed in positive matches:

dispatcherservletautoconfiguration  

Embeddedservletcontainerautoconfiguration

Errormvcautoconfiguration

Httpencodingautoconfiguration

Httpmessageconvertersautoconfiguration

Jacksonautoconfiguration

Jmxautoconfiguration

Multipartautoconfiguration

Serverpropertiesautoconfiguration

Propertyplaceholderautoconfiguration

Thymeleafautoconfiguration

Webmvcautoconfiguration

Websocketautoconfiguration

Then, to update the project configuration, introduce these components explicitly, and then run the application to ensure that no errors occur:
@Configuration

@Import ({

Dispatcherservletautoconfiguration. class,

Embeddedservletcontainerautoconfiguration. class,

Errormvcautoconfiguration. class,

Httpencodingautoconfiguration. class,

Httpmessageconvertersautoconfiguration. class,

Jacksonautoconfiguration. class,

Jmxautoconfiguration. class,

Multipartautoconfiguration. class,

Serverpropertiesautoconfiguration. class,

Propertyplaceholderautoconfiguration. class,

Thymeleafautoconfiguration. class,

Webmvcautoconfiguration. class,

Websocketautoconfiguration. class,

})

public class App {

In the above code, we can delete the component information that we do not need, to very high application performance, such as not using JMX and WebSocket function in the project, then we can remove jmxautoconfiguration. class and the Websocketautoconfiguration. class .

Once deleted, run the project again to make sure everything is OK.

(8) Summary

In this article we show you how to speed up Spring boot Quick Start, the main idea is that obsolete @springbootapplication explicitly introduce the components we need.

Next trailer: Introduction to High-performance Web server Undertow, in the next article on how to replace Tomcat using Undertow for memory optimization.

Springboot Start too slow optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.