Master Spring Boot 3.2.5: Custom Failure Analyzer, Environment & Web Server Settings

This guide walks through creating custom FailureAnalyzers, registering EnvironmentPostProcessors, configuring non‑web applications, switching profiles for YAML settings, altering the embedded web server, and customizing server factories in Spring Boot 3.2.5, complete with code examples and screenshots.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot 3.2.5: Custom Failure Analyzer, Environment & Web Server Settings

1. Failure Analysis

Spring Boot allows intercepting startup exceptions via the FailureAnalyzer interface, which returns a FailureAnalysis instance. Returning null lets other analyzers run. Example implementation:

public class PackAbstractFailureAnalyzer extends AbstractFailureAnalyzer<NullPointerException> {
    @Override
    protected FailureAnalysis analyze(Throwable rootFailure, NullPointerException cause) {
        System.err.println(rootFailure.getMessage());
        System.out.printf("发生了空指针异常:%s%n", cause);
        return new FailureAnalysis(rootFailure.getMessage(), cause.getMessage(), cause);
    }
}

Register the analyzer in META-INF/spring.factories:

org.springframework.boot.diagnostics.FailureAnalyzer=\
com.pack.test.failure_analyzer.PackAbstractFailureAnalyzer

Trigger a startup exception manually:

@Bean
User user() {
    String name = null;
    System.out.println(name.charAt(0));
    return new User(666L, "李四");
}

Application start output:

2. Custom Environment Before Startup

During startup, before ApplicationContext is instantiated, Spring Boot publishes ApplicationEnvironmentPreparedEvent , which is handled by EnvironmentPostProcessorApplicationListener . Implement EnvironmentPostProcessor to add custom properties.

public class PackEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Resource path = new ClassPathResource("com/pack/test/environment_post_processor/config.yml");
        PropertySource<?> propertySource = loadYaml(path);
        environment.getPropertySources().addLast(propertySource);
    }

    private PropertySource<?> loadYaml(Resource path) {
        Assert.isTrue(path.exists(), () -> "Resource " + path + " does not exist");
        try {
            return this.loader.load("custom-resource", path).get(0);
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
        }
    }
}

YAML file ( config.yml) content:

app:
  version: 1.0.0
  name: myapp

Register in META-INF/spring.factories:

org.springframework.boot.env.EnvironmentPostProcessor=\
com.pack.test.environment_post_processor.PackEnvironmentPostProcessor

Test the injected properties:

@Resource
private Environment env;

System.out.printf("version: %s, name: %s%n", 
        env.getProperty("app.version"), 
        env.getProperty("app.name"));
// Output: version: 1.0.0, name: myapp

3. Creating a Non‑Web Application

By default Spring Boot starts a web application when the web starter is on the classpath. To run a non‑web app, either set the type programmatically:

SpringApplication app = new SpringApplication(Application.class);
app.setWebApplicationType(WebApplicationType.NONE);
app.run(args);

or configure it in application.yml:

spring:
  main:
    web-application-type: none

With this configuration, the JVM exits after all non‑daemon threads finish.

4. Profile‑Based Configuration

Spring Boot can activate different YAML documents based on the active profile. Example:

spring:
  config:
    activate:
      on-profile: dev
server:
  port: 9001
---
spring:
  config:
    activate:
      on-profile: prod
server:
  port: 8080

Activate a profile with:

spring:
  profiles:
    active:
    - dev

When the dev profile is active, the application starts on port 9001.

5. Web Service Customization

The default embedded server is Tomcat. To switch to Jetty, exclude Tomcat and add the Jetty starter:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Undertow can be used similarly with spring-boot-starter-undertow.

To disable HTTP endpoints while still creating a WebApplicationContext:

server:
  port: -1

For a random port:

server:
  port: 0

Retrieve the actual port after startup via WebServerInitializedEvent :

@Component
public class PackWebServerListener implements ApplicationListener<WebServerInitializedEvent> {
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        System.out.printf("服务运行端口: %d%n", event.getWebServer().getPort());
    }
}

In tests, obtain the random port with:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationTests {
    @LocalServerPort
    private int port;

    @Test
    public void contextLoads() {
        System.out.printf("测试随机端口: %d%n", port);
    }
}

6. Custom Web Server

For fine‑grained server tweaks, implement WebServerFactoryCustomizer for the specific server type (Tomcat, Jetty, Undertow, Netty). Example for Tomcat:

@Component
public class PackTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // custom Tomcat settings here
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendjavaspring-bootfailure-analyzerweb-server
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.