Member-only story

Create better Spring libraries with @Enable… Annotations

Görkem Gök
3 min readJan 1, 2023

--

Photo by Iñaki del Olmo on Unsplash

You can find the sample code in the following repo: https://github.com/gorkemgok/enabler-annotation-example

Sometimes, we create libraries to make some functionalities reusable for multiple applications. When those libraries have some beans to be registered in the spring context, the developers tend to use @ComponentScan or @Import annotations in the application. By doing this, the application is made highly dependent on the library's internal structure and the author of the library loses control over the design.

Let’s say we have a spring rest application and we want to create a library to add some common headers (such as X-Host and X-Trace-Id) to the responses.

To do that we would have two request filters in our library as followings:

Consider that those two classes are in different jar files and (probably) in different packages than the user application. The users of this library have two options to use those filters in their applications. @Import them or scan the library package with @ComponentScan.

Both of those options take control from the author of the library. Any internal change in the library can break the build of the user application or even worse introduce a runtime error. Let’s say we introduce a dependency which is TraceIdGenerator in TraceIdHeaderFilter.

--

--

Görkem Gök
Görkem Gök

Written by Görkem Gök

Developer | Software Craftsmanship Enthusiast | Physicist

No responses yet

Write a response