Spring Developer Tools Source analysis: Three, restart automatic configuration

Source: Internet
Author: User
Tags event listener static class

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

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

In the localdevtoolsautoconfiguration mainly contains the Livereload and restart of the configuration, livereload follow-up to see the situation again, here first value the configuration of the start. 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 is started.

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

When you launch a project through the IDE, the conditions here are met by default, and other configurations in Localdevtoolsautoconfiguration can take effect. 3.2 restartconfiguration Restart configuration

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

There are also restrictions on restartconfiguration, which do not take effect until the following parameters are set:

Spring.devtools.restart.enabled=false

Not set or set to any value that is not false (ignoring case) will take effect.

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

Here's a look at each configuration in Restartconfiguration. 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 method of the interface is called in the future.

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

This method allows you to see if the trigger file is configured (only if the specified file will be restarted) when the FileSystemWatcher is created, and whether additional locations need to be monitored for changes are configured. 3.2.2 Classpathrestartstrategy Restart policy

The code is as follows:

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

The method returns the Patternclasspathrestartstrategy implementation class, judging whether to restart, ignoring all incoming locations, the default is to ignore the following location:

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 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 it is created, the classpath is obtained from Restarter, which is described in detail later, and a watcher is created, using the two beans created earlier. Setstopwatcheronrestart means that when class paths change and need to be restarted, class monitoring is stopped and true is set to stop monitoring before restarting.

If monitoring is stopped before restarting, we may need to worry about what to do if the configuration is wrong to cause Spring to fail to start, Devtools also provides the appropriate policy to resolve this issue, as the next section will see. 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, which is invoked when the event is triggered. In the previous article, we introduced the Classpathchangedevent, which contains the restartrequired, which will determine if a restart is required, and when a restart is required, an instance of Restarter is called to reboot.

Filewatchingfailurehandler was also passed in the restart method and Filesystemwatcherfactory was used.

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

A new file monitoring is created through filesystemwatcherfactory in Filewatchingfailurehandler, when the content of the classpath changes (no need to consider whether a restart is required because it has stopped, And does not start successfully) try restarting it. This strategy can be resolved when the configuration or code error fails to start, you can modify the bug to resolve the error, and then Devtools automatically try to start.

Filewatchingfailurehandler in FileSystemWatcher and 3.2.3 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 a change since the restart, because the restart takes time, which will cause the restart is not over the achievements and reboot, in this case, in addition to errors, but also because of a short period of frequent restart caused by the restart time is too long.

On restart, 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 there is no conflict with the FileSystemWatcher here anyway. 3.3 Re-initializes Spring after reboot

When you turn off restart, the main method of our own Xxapplication class is devtools through reflection, so localdevtoolsautoconfiguration is reinitialized and classpath monitoring is re-established. We are now only aware of the process of starting and triggering reboots from file monitoring, classpath monitoring, and monitoring configuration. There are a number of key processing processes related to Restartclassloader and Restarter, and in order to prevent too long the focus is too fragmented, the two sections are described separately in the following paragraphs.

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.