Video in progress

Strong Middle 🧭 Design patterns

You need to add a Decorator to a ready-made Spring bean without changing it. What ways do you have to do that?

The simplest is to wrap the original implementation in your own @Bean method and mark it @Primary. To wrap library beans, or many beans the same way, you use a BeanPostProcessor; for cross-cutting concerns an AOP aspect is more convenient.

📖 Answer

The task: add metrics and retry to ExchangeRateClient (an external API) without changing the 15 places that use it.

Way 1, assemble by hand:

@Configuration
class RateConfig {
    @Bean
    HttpRateClient httpRateClient(RestClient client) { return new HttpRateClient(client); }

    @Bean
    @Primary
    ExchangeRateClient rateClient(HttpRateClient http, MeterRegistry registry) {
        return new MeteredRateClient(new RetryingRateClient(http, 3), registry);
    }
}

Everything is visible, and the order of the layers is in the code. Without @Primary, injection would conflict because two beans have the same type, which is why the original implementation is declared with its concrete type.

Way 2, BeanPostProcessor:

@Component
class RateClientDecorator implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        if (bean instanceof ExchangeRateClient c && !(bean instanceof MeteredRateClient)) {
            return new MeteredRateClient(c, Metrics.globalRegistry);
        }
        return bean;
    }
}

It's convenient if you didn't create the bean (it came from auto-configuration) or you need to wrap all implementations of an interface. The downside: a BeanPostProcessor is created very early, and if you inject other beans into it, they may miss post-processing themselves (the log shows the warning "is not eligible for getting processed by all BeanPostProcessors").

Way 3, an @Around aspect. Good for things that apply to many beans, like logging, metrics and timing; but for adding specific business behavior to a single bean, an aspect is hidden and hard to find.

I usually start with way 1: configuration you can read and debug is worth more than a magical post-processor.