DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Component Tests for Spring Cloud Microservices
  • Spring Boot - Tracing Micro Service Logs | Log Tracing In Microservices With Spring Cloud Sleuth
  • How to Create Microservices Using Spring

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Java Virtual Threads and Scaling
  • Unlocking AI Coding Assistants Part 2: Generating Code
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  1. DZone
  2. Coding
  3. Frameworks
  4. A Post-Processor for Spring Boot

A Post-Processor for Spring Boot

Learn how to make your own post-processor for your Spring Boot needs, allowing you to add to your environment with ease.

By 
Nicolas Fränkel user avatar
Nicolas Fränkel
DZone Core CORE ·
Nov. 23, 16 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
26.3K Views

Join the DZone community and get the full member experience.

Join For Free

Most Spring developers know about the BeanPostProcessor and the BeanFactoryPostProcessor classes. The former enables changes to new bean instances before they can be used, while the latter lets you modify bean definitions — the metadata to create the bean. Common use-cases include:

  • Bootstrapping processing of @Configuration classes, via ConfigurationClassPostProcessor
  • Resolving ${...} placeholders, through PropertyPlaceholderConfigurer
  • Autowiring of annotated fields, setter methods and arbitrary config methods — AutowiredAnnotationBeanPostProcessor
  • And so on, and so forth…

Out-of-the-box and custom post-processors are enough to meet most requirements regarding the Spring Framework proper.

Then comes Spring Boot, with its convention over configuration approach. Among its key features is the ability to read configuration from different sources, such as the default application.properties, the default application.yml, another configuration file and/or System properties passed on the command line. What happens behind the scene is that they all are merged into an Environment instance. This object can then be injected into any bean and queried for any value by passing the key.

As a starter designer, how to define a default configuration value? Obviously, it cannot be set via a Spring @Bean-annotated method. Let’s analyze the Spring Cloud Sleuth starter as an example:

Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from Dapper, Zipkin, and HTrace. For most users Sleuth should be invisible, and all your interactions with external systems should be instrumented automatically. You can capture data simply in logs, or by sending it to a remote collector service.

Regarding the configuration, the starter changes the default log format to display additional information (to be specific, span and trace IDs but that’s not relevant to the post). Let’s dig further.

As for auto-configuration classes, the magic starts in the META-INF/spring.factories file in the Spring Cloud Sleuth starter JAR:

# Environment Post Processor
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.sleuth.autoconfig.TraceEnvironmentPostProcessor

The definition of the interface looks like the following:

public interface EnvironmentPostProcessor {
  void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application);
}

And the implementation like that:

public class TraceEnvironmentPostProcessor implements EnvironmentPostProcessor {

  private static final String PROPERTY_SOURCE_NAME = "defaultProperties";

  @Override
  public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("logging.pattern.level",
      "%clr(%5p) %clr([${spring.application.name:},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]){yellow}");
    map.put("spring.aop.proxyTargetClass", "true");
    addOrReplace(environment.getPropertySources(), map);
  }

  private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
    MapPropertySource target = null;
    if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
      PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
      if (source instanceof MapPropertySource) {
        target = (MapPropertySource) source;
        for (String key : map.keySet()) {
          if (!target.containsProperty(key)) {
            target.getSource().put(key, map.get(key));
          }
        }
      }
    }
    if (target == null) {
      target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
    }
    if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
      propertySources.addLast(target);
    }
  }
}

As can be seen, the implementation will add both the logging.pattern.level and the spring.aop.proxyTargetClass properties (with relevant values) to the environment (if they don’t exist yet). If they do, they will be added at the bottom of the list.

With @Conditional, starters can provide default beans in auto-configuration classes, while with EnvironmentPostProcessor, they can provide default property values as well. Using both in conjunction can go a long way toward offering a great convention over configuration Spring Boot experience when designing your own starter.

Spring Framework Spring Boot Spring Cloud Convention over configuration

Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Component Tests for Spring Cloud Microservices
  • Spring Boot - Tracing Micro Service Logs | Log Tracing In Microservices With Spring Cloud Sleuth
  • How to Create Microservices Using Spring

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!