How to make a bean initialize before DataSource without excluding auto‑configuration

16 hours ago 1
ARTICLE AD BOX

I have a Spring Boot application that relies on the default DataSourceAutoConfiguration to create my DataSource bean. I also have a custom bean that must be fully initialized before the DataSource bean is created (e.g., to set up some infrastructure that the DataSource depends on).

Here's a simplified example of the bean I want to be initialized first:

@Component public class MyEarlyBean { public MyEarlyBean() { System.out.println("MyEarlyBean initialized"); // some important setup } }

I want MyEarlyBean to be created before the DataSource bean, but I want to keep Spring Boot's auto‑configuration for the DataSource.

What I have tried

Using @DependsOn on the DataSource bean – This would require me to define my own DataSource bean (or exclude auto‑configuration) so that I can annotate it with @DependsOn("myEarlyBean").
That works, but I lose the convenience of auto‑configuration and have to manually configure the DataSource (connection pool, properties, etc.).

Using @AutoConfigureBefore – I created an auto‑configuration class with @AutoConfigureBefore(DataSourceAutoConfiguration.class) and defined MyEarlyBean inside it.
This ensures the auto‑configuration class is processed early, but the bean itself might still be instantiated after DataSource because @AutoConfigureBefore only orders auto‑configuration classes, not the beans they contain.

Implementing a BeanFactoryPostProcessor – I wrote a custom BeanFactoryPostProcessor that scans for beans with a custom annotation and adds them to the dependsOn of the DataSource bean. This works, but it feels like a lot of boilerplate for what seems like a common need.

My question

Is there a simpler, built‑in way to declare that a bean should be initialized before a specific auto‑configured bean (like DataSource) without having to manually define that target bean or write a custom post‑processor?

I'm looking for something that works declaratively, similar to how @DependsOn works but on the prerequisite side – i.e., a way to say “this bean must be ready before bean X”, rather than modifying bean X's definition.

Why I think this is useful

Many real‑world applications have setup beans that need to run before infrastructure beans like DataSource, JdbcTemplate, etc. Auto‑configuration is a core feature of Spring Boot, and being able to influence initialization order without breaking it would be very helpful.

If there's no built‑in support, what is the most elegant and least invasive workaround? Any advice would be greatly appreciated.


I am considering proposing a feature like @RequiredBy to the Spring team – but for now, I need a practical solution. If you have experience with similar requirements, please share your approach.

Read Entire Article