Spring Developer Tools Source analysis: Three, restart automatic configuration

Source: Internet
Author: User
Tags event listener static class

Next Spring Developer Tools Source Analysis: Second, class path monitoring, then look at the previous mentioned how these classes are configured, how to start.

Spring-boot-devtools uses the automatic configuration of Spring boot, we first focus on the automatic restart in the local development environment.

In the localdevtoolsautoconfiguration mainly includes the livereload and the reset configuration, the livereload later looks the situation to introduce again, here first values the Kai configuration. 3.1 localdevtoolsautoconfiguration Local configuration

@Configuration
@ConditionalOnInitializedRestarter
@EnableConfigurationProperties ( Devtoolsproperties.class) Public
class Localdevtoolsautoconfiguration {

On this class @ConditionalOnInitializedRestarter is a condition in which the configuration takes effect, and the implementation will determine whether Restarter has been instantiated and whether there is a class directory that can be monitored (except for directories outside the jar file), if it has been instantiated , and a directory that needs to be monitored will start.

When started by Java-jar, the Devtools does not trigger subsequent configurations because there is no directory to monitor, so the restarter is not monitored, but the directory is not automatically restarted.

When you start the project through the IDE, the conditions here are met by default, and other configurations in the localdevtoolsautoconfiguration can take effect. 3.2 restartconfiguration reboot configuration

/**
 * Local restart Configuration.
 * *
@Configuration
@ConditionalOnProperty (
    prefix = "Spring.devtools.restart", 
    name = "Enabled", 
    matchifmissing = True)
Static Class Restartconfiguration {

There are also restrictions on restartconfiguration that do not take effect only if the following parameters are set:

Spring.devtools.restart.enabled=false

is not set or set to any value that is not false (ignores case), it will take effect.

In addition to this parameter can be controlled, there is a direct control of the Restarter whether the effective parameters, follow-up will be introduced.

Look at each of the configurations in the restartconfiguration below. 3.2.1 Filesystemwatcherfactory File monitoring

The configuration code is as follows:

@Bean public
filesystemwatcherfactory filesystemwatcherfactory () {return
    this::newfilesystemwatcher;
}

Private FileSystemWatcher Newfilesystemwatcher () {
    Restart restartproperties = This.properties.getRestart ();
    FileSystemWatcher watcher = new FileSystemWatcher (True,
            restartproperties.getpollinterval (),
            Restartproperties.getquietperiod ());
    String triggerfile = Restartproperties.gettriggerfile ();
    if (Stringutils.haslength (Triggerfile)) {
        watcher.settriggerfilter (new Triggerfilefilter (Triggerfile));
    }
    list<file> additionalpaths = Restartproperties.getadditionalpaths ();
    for (File path:additionalpaths) {
        Watcher.addsourcefolder (Path.getabsolutefile ());
    }
    return watcher;
}

Filesystemwatcherfactory is a functional interface, where a method reference is returned directly. The following Newfilesystemwatcher method is executed when the interface's methods are called in the future.

Each time the Filesystemwatcherfactory () method is invoked, the same filesystemwatcherfactory is returned, but the call to the factory's Getfilesystemwatcher () method returns a new FileSystemWatcher.

In this way, you can see that when you create FileSystemWatcher, you will determine if you have a trigger file configured (only if you modify the specified file to reboot) and if you are configuring additional locations to monitor for changes. 3.2.2 Classpathrestartstrategy Restart Strategy

The code is as follows:

@Bean
@ConditionalOnMissingBean public
classpathrestartstrategy classpathrestartstrategy () {
    return New Patternclasspathrestartstrategy (
            This.properties.getRestart (). Getallexclude ());

This method returns the Patternclasspathrestartstrategy implementation class, which determines whether to reboot, ignores all incoming locations, and ignores the default locations as follows:

private static final String default_restart_excludes = "meta-inf/maven/**,"
        + "meta-inf/resources/**,resources/** , static/**,public/**,templates/**, "
        +" **/*test.class,**/*tests.class,git.properties,meta-inf/ Build-info.properties ";

Additional exclusions can be set by using the following parameters:

Spring.devtools.restart.additional-exclude=
3.2.3 Classpathfilesystemwatcher class path monitoring

The code is as follows:

@Bean
@ConditionalOnMissingBean public
classpathfilesystemwatcher Classpathfilesystemwatcher () {
    url[ ] URLs = restarter.getinstance (). Getinitialurls ();
    Classpathfilesystemwatcher watcher = new Classpathfilesystemwatcher (
            filesystemwatcherfactory (), Classpathrestartstrategy (), URLs);
    Watcher.setstopwatcheronrestart (true);
    return watcher;
}

When created here, the Classpath (described later in detail) was obtained from Restarter and then a watcher was created, using the two beans previously created. Setstopwatcheronrestart means stopping class monitoring when the classpath changes and needs to be restarted, where true is set, which stops monitoring before restarting.

If monitoring is stopped before rebooting, we may need to worry about what to do if the configuration is wrong and cause Spring to fail to start, and Devtools also provides the appropriate strategy to solve the problem, as you'll see in the next section. 3.2.3 Monitor Classpathchangedevent

The code is as follows:

@EventListener public
void Onclasspathchanged (Classpathchangedevent event) {
    if (event.isrestartrequired ()) {
        restarter.getinstance (). Restart (
                new Filewatchingfailurehandler (Filesystemwatcherfactory ()));
    }

When a method adds a @EventListener, Spring adds the method to the event listener, and the method is invoked when the event is triggered. In the previous article introduced Classpathchangedevent, which contains the restartrequired, here will determine whether the need to reboot, when the need to reboot, it will invoke the Restarter instance to restart.

The Filewatchingfailurehandler is also passed in to the restart method and the filesystemwatcherfactory is used.

Filewatchingfailurehandler implements the Failurehandler interface, which is used in the startup process of the reboot, if there is an error, what strategy to take to proceed, the interface method returns only two results, Outcome.abort Abort or Outcome.retry retry.

In Filewatchingfailurehandler, a new file monitor is created by Filesystemwatcherfactory, when the content of the classpath changes (no need to consider whether a reboot is required, because it has stopped, And did not start successfully), try to reboot. This strategy resolves the bug resolution error when the configuration or code error cannot be started, and then Devtools automatically attempts to start.

The FileSystemWatcher and 3.2.3 in the Filewatchingfailurehandler are not the same, and the other is closed before restarting, and the purpose of the shutdown is not to prevent conflicts with the presence of two monitors, but to prevent the first modification , there has been no restart when the change, because the reboot takes time, which will cause the restart is not finished and restarted, in addition to the error will be caused by frequent restart in a short time cause the restart time is too long.

When rebooting, all Spring context is closed, and the Destroy method in Classpathfilesystemwatcher is also triggered:

@Override public
Void Destroy () throws Exception {
    this.fileSystemWatcher.stop ();
}

File monitoring is also turned off in destroy, so it doesn't conflict with the FileSystemWatcher here anyway. Spring will be reinitialized after 3.3 reboot

When the Devtools is turned off, the main method of our own Xxapplication class is executed by reflection, so localdevtoolsautoconfiguration is reinitialized and the CLASSPATH monitoring is also established. We are now only aware of the process from file monitoring, classpath monitoring, and monitoring of configuration initiation and triggering of reboots. There are a number of key processes related to Restartclassloader and restarter, and to prevent too much space from being too fragmented, the following sections are described separately.

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.