Allow modules to contribute to Devtools' default properties

Closes gh-44792
This commit is contained in:
Andy Wilkinson
2025-10-15 20:19:02 +01:00
parent aab6375702
commit 55e7c83498
20 changed files with 112 additions and 84 deletions
@@ -16,22 +16,24 @@
package org.springframework.boot.build.devtools;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
/**
@@ -41,22 +43,22 @@ import org.gradle.api.tasks.TaskAction;
*/
public abstract class DocumentDevtoolsPropertyDefaults extends DefaultTask {
private final Configuration devtools;
private FileCollection defaults;
public DocumentDevtoolsPropertyDefaults() {
this.devtools = getProject().getConfigurations().create("devtools");
getOutputFile().convention(getProject().getLayout()
.getBuildDirectory()
.file("generated/docs/using/devtools-property-defaults.adoc"));
Map<String, String> dependency = new HashMap<>();
dependency.put("path", ":module:spring-boot-devtools");
dependency.put("configuration", "propertyDefaults");
this.devtools.getDependencies().add(getProject().getDependencies().project(dependency));
}
@InputFiles
public FileCollection getDevtools() {
return this.devtools;
@PathSensitive(PathSensitivity.RELATIVE)
public FileCollection getDefaults() {
return this.defaults;
}
public void setDefaults(FileCollection defaults) {
this.defaults = defaults;
}
@OutputFile
@@ -64,23 +66,36 @@ public abstract class DocumentDevtoolsPropertyDefaults extends DefaultTask {
@TaskAction
void documentPropertyDefaults() throws IOException {
Map<String, String> properties = loadProperties();
documentProperties(properties);
Map<String, String> propertyDefaults = loadPropertyDefaults();
documentPropertyDefaults(propertyDefaults);
}
private Map<String, String> loadProperties() throws IOException, FileNotFoundException {
private Map<String, String> loadPropertyDefaults() throws IOException, FileNotFoundException {
Properties properties = new Properties();
Map<String, String> sortedProperties = new TreeMap<>();
try (FileInputStream stream = new FileInputStream(this.devtools.getSingleFile())) {
properties.load(stream);
for (String name : properties.stringPropertyNames()) {
sortedProperties.put(name, properties.getProperty(name));
Map<String, String> propertyDefaults = new TreeMap<>();
for (File contribution : this.defaults.getFiles()) {
if (contribution.isFile()) {
try (JarFile jar = new JarFile(contribution)) {
ZipEntry entry = jar.getEntry("META-INF/spring-devtools.properties");
if (entry != null) {
properties.load(jar.getInputStream(entry));
}
}
}
else if (contribution.exists()) {
throw new IllegalStateException(
"Unexpected Devtools default properties contribution from '" + contribution + "'");
}
}
return sortedProperties;
for (String name : properties.stringPropertyNames()) {
if (name.startsWith("defaults.")) {
propertyDefaults.put(name.substring("defaults.".length()), properties.getProperty(name));
}
}
return propertyDefaults;
}
private void documentProperties(Map<String, String> properties) throws IOException {
private void documentPropertyDefaults(Map<String, String> properties) throws IOException {
try (PrintWriter writer = new PrintWriter(new FileWriter(getOutputFile().getAsFile().get()))) {
writer.println("[cols=\"3,1\"]");
writer.println("|===");
@@ -0,0 +1,3 @@
defaults.spring.template.provider.cache=false
defaults.spring.web.resources.cache.period=0
defaults.spring.web.resources.chain.cache=false
@@ -0,0 +1 @@
defaults.spring.docker.compose.readiness.wait=only-if-started
+7 -1
View File
@@ -322,6 +322,10 @@ aggregates {
category = Category.DOCUMENTATION
usage = "test-slice-metadata"
}
devtoolsPropertyDefaults {
category = Category.LIBRARY
usage = "java-runtime"
}
}
tasks.register("documentTestSlices", org.springframework.boot.build.test.autoconfigure.DocumentTestSlices) {
@@ -363,7 +367,9 @@ tasks.register("documentConfigurationProperties", org.springframework.boot.build
outputDir = layout.buildDirectory.dir("generated/docs/application-properties")
}
tasks.register("documentDevtoolsPropertyDefaults", org.springframework.boot.build.devtools.DocumentDevtoolsPropertyDefaults) {}
tasks.register("documentDevtoolsPropertyDefaults", org.springframework.boot.build.devtools.DocumentDevtoolsPropertyDefaults) {
defaults = aggregates.devtoolsPropertyDefaults.files
}
tasks.register("runRemoteSpringApplicationExample", org.springframework.boot.build.docs.ApplicationRunner) {
classpath = configurations.remoteSpringApplicationExample
-8
View File
@@ -29,13 +29,6 @@ configurations {
intTestDependencies {
extendsFrom dependencyManagement
}
propertyDefaults
}
artifacts {
propertyDefaults(file("build/resources/main/org/springframework/boot/devtools/env/devtools-property-defaults.properties")) {
builtBy(processResources)
}
}
dependencies {
@@ -60,7 +53,6 @@ dependencies {
intTestImplementation("org.apache.httpcomponents.client5:httpclient5")
intTestImplementation("net.bytebuddy:byte-buddy")
intTestRuntimeOnly("org.springframework:spring-web")
optional(project(":module:spring-boot-jdbc"))
@@ -16,12 +16,8 @@
package org.springframework.boot.devtools.env;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.jspecify.annotations.Nullable;
@@ -30,6 +26,7 @@ import org.springframework.boot.EnvironmentPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.devtools.logger.DevToolsLogFactory;
import org.springframework.boot.devtools.restart.Restarter;
import org.springframework.boot.devtools.settings.DevToolsSettings;
import org.springframework.boot.devtools.system.DevToolsEnablementDeducer;
import org.springframework.core.NativeDetector;
import org.springframework.core.Ordered;
@@ -69,7 +66,7 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro
PROPERTIES = Collections.emptyMap();
}
else {
PROPERTIES = loadDefaultProperties();
PROPERTIES = DevToolsSettings.get().getPropertyDefaults();
}
}
@@ -133,24 +130,4 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro
}
}
private static Map<String, Object> loadDefaultProperties() {
Properties properties = new Properties();
try (InputStream stream = DevToolsPropertyDefaultsPostProcessor.class
.getResourceAsStream("devtools-property-defaults.properties")) {
if (stream == null) {
throw new RuntimeException(
"Failed to load devtools-property-defaults.properties because it doesn't exist");
}
properties.load(stream);
}
catch (IOException ex) {
throw new RuntimeException("Failed to load devtools-property-defaults.properties", ex);
}
Map<String, Object> map = new HashMap<>();
for (String name : properties.stringPropertyNames()) {
map.put(name, properties.getProperty(name));
}
return Collections.unmodifiableMap(map);
}
}
@@ -18,7 +18,9 @@ package org.springframework.boot.devtools.settings;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -52,14 +54,23 @@ public class DevToolsSettings {
private final List<Pattern> restartExcludePatterns = new ArrayList<>();
private final Map<String, Object> propertyDefaults = new HashMap<>();
DevToolsSettings() {
}
void add(Map<?, ?> properties) {
private void add(Map<?, ?> properties) {
Map<String, Pattern> includes = getPatterns(properties, "restart.include.");
this.restartIncludePatterns.addAll(includes.values());
Map<String, Pattern> excludes = getPatterns(properties, "restart.exclude.");
this.restartExcludePatterns.addAll(excludes.values());
properties.forEach((key, value) -> {
String name = String.valueOf(key);
if (name.startsWith("defaults.")) {
name = name.substring("defaults.".length());
this.propertyDefaults.put(name, value);
}
});
}
private Map<String, Pattern> getPatterns(Map<?, ?> properties, String prefix) {
@@ -82,6 +93,10 @@ public class DevToolsSettings {
return isMatch(url.toString(), this.restartExcludePatterns);
}
public Map<String, Object> getPropertyDefaults() {
return Collections.unmodifiableMap(this.propertyDefaults);
}
private boolean isMatch(String url, List<Pattern> patterns) {
for (Pattern pattern : patterns) {
if (pattern.matcher(url).find()) {
@@ -1,17 +0,0 @@
server.error.include-binding-errors=always
server.error.include-message=always
server.error.include-stacktrace=always
server.servlet.jsp.init-parameters.development=true
server.servlet.session.persistent=true
spring.freemarker.cache=false
spring.graphql.graphiql.enabled=true
spring.groovy.template.cache=false
spring.h2.console.enabled=true
spring.mustache.servlet.cache=false
spring.mvc.log-resolved-exception=true
spring.reactor.netty.shutdown-quiet-period=0s
spring.template.provider.cache=false
spring.thymeleaf.cache=false
spring.web.resources.cache.period=0
spring.web.resources.chain.cache=false
spring.docker.compose.readiness.wait=only-if-started
@@ -18,7 +18,6 @@ package org.springframework.boot.devtools.env;
import java.net.URL;
import java.util.Collections;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
@@ -31,9 +30,10 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.devtools.restart.RestartInitializer;
import org.springframework.boot.devtools.restart.Restarter;
import org.springframework.boot.testsupport.classpath.ForkedClassPath;
import org.springframework.boot.testsupport.classpath.resources.WithResource;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -65,6 +65,8 @@ class DevToolPropertiesIntegrationTests {
}
@Test
@ForkedClassPath
@WithResource(name = "META-INF/spring-devtools.properties", content = "defaults.com.example.enabled=true")
void classPropertyConditionIsAffectedByDevToolProperties() throws Exception {
SpringApplication application = new SpringApplication(ClassConditionConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
@@ -73,6 +75,8 @@ class DevToolPropertiesIntegrationTests {
}
@Test
@ForkedClassPath
@WithResource(name = "META-INF/spring-devtools.properties", content = "defaults.com.example.enabled=true")
void beanMethodPropertyConditionIsAffectedByDevToolProperties() throws Exception {
SpringApplication application = new SpringApplication(BeanConditionConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
@@ -81,6 +85,8 @@ class DevToolPropertiesIntegrationTests {
}
@Test
@ForkedClassPath
@WithResource(name = "META-INF/spring-devtools.properties", content = "defaults.com.example.enabled=true")
void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception {
Restarter.clearInstance();
Restarter.disable();
@@ -94,6 +100,8 @@ class DevToolPropertiesIntegrationTests {
}
@Test
@ForkedClassPath
@WithResource(name = "META-INF/spring-devtools.properties", content = "defaults.com.example.enabled=true")
void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception {
Restarter.clearInstance();
Restarter.disable();
@@ -105,17 +113,20 @@ class DevToolPropertiesIntegrationTests {
}
@Test
void postProcessEnablesIncludeStackTraceProperty() throws Exception {
@ForkedClassPath
@WithResource(name = "META-INF/spring-devtools.properties", content = """
defaults.com.example.one=alpha
defaults.com.example.two=bravo
""")
void postProcessSetsPropertyDefaults() throws Exception {
SpringApplication application = new SpringApplication(TestConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
this.context = getContext(application::run);
ConfigurableEnvironment environment = this.context.getEnvironment();
String includeStackTrace = environment.getProperty("server.error.include-stacktrace");
assertThat(includeStackTrace)
.isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH));
String includeMessage = environment.getProperty("server.error.include-message");
assertThat(includeMessage)
.isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH));
String one = environment.getProperty("com.example.one");
assertThat(one).isEqualTo("alpha");
String two = environment.getProperty("com.example.two");
assertThat(two).isEqualTo("bravo");
}
protected ConfigurableApplicationContext getContext(Supplier<ConfigurableApplicationContext> supplier)
@@ -138,7 +149,7 @@ class DevToolPropertiesIntegrationTests {
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty("spring.h2.console.enabled")
@ConditionalOnProperty("com.example.enabled")
static class ClassConditionConfiguration {
}
@@ -147,7 +158,7 @@ class DevToolPropertiesIntegrationTests {
static class BeanConditionConfiguration {
@Bean
@ConditionalOnProperty("spring.h2.console.enabled")
@ConditionalOnProperty("com.example.enabled")
MyBean myBean() {
return new MyBean();
}
@@ -19,6 +19,7 @@ package org.springframework.boot.devtools.settings;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -60,6 +61,14 @@ class DevToolsSettingsTests {
assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-starter-some-thing"))).isTrue();
}
@Test
void propertyDefaults() {
DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-defaults.properties");
Map<String, Object> propertyDefaults = settings.getPropertyDefaults();
assertThat(propertyDefaults)
.containsExactlyInAnyOrderEntriesOf(Map.of("com.example.a", "true", "com.example.b", "17"));
}
private URL makeUrl(File file, String name) throws IOException {
file = new File(file, name);
file = new File(file, "build");
@@ -0,0 +1,3 @@
defaults.com.example.a=true
defaults.com.example.b=17
@@ -0,0 +1 @@
defaults.spring.freemarker.cache=false
@@ -0,0 +1 @@
defaults.spring.graphql.graphiql.enabled=true
@@ -0,0 +1 @@
defaults.spring.groovy.template.cache=false
@@ -0,0 +1 @@
defaults.spring.h2.console.enabled=true
@@ -0,0 +1 @@
defaults.spring.mustache.servlet.cache=false
@@ -0,0 +1 @@
defaults.spring.reactor.netty.shutdown-quiet-period=0s
@@ -0,0 +1 @@
defaults.spring.thymeleaf.cache=false
@@ -0,0 +1,5 @@
defaults.server.error.include-binding-errors=always
defaults.server.error.include-message=always
defaults.server.error.include-stacktrace=always
defaults.server.servlet.jsp.init-parameters.development=true
defaults.server.servlet.session.persistent=true
@@ -0,0 +1 @@
defaults.spring.mvc.log-resolved-exception=true