Understanding the @DependsOn Annotation in Spring

Author:

Introduction to the @DependsOn Annotation

This annotation tells Spring that the bean marked with this annotation should be created after the beans that it depends on are initialized.

You can specify the beans you need to be created first in the @DependsOn annotation parameters.

This annotation is used when a bean does not explicitly depend on the other bean (as a configuration or argument). But it can rely on the other bean’s behavior or actions.

It can be used on the stereotype annotations (like @Component, @Service, etc.) or in methods annotated with @Bean.

Example Scenario Using @DependsOn

Suppose your application has a set of parameters in the database, that is cached by a CacheManager bean. This bean fetches all the parameter data and puts it into a cache.

But to fetch this parameter, CacheManager needs the ParameterInitializer to fill the data into the database first so CacheManager can read it.

So the CacheManager depends on the ParameterInitializer execution to cache the parameter data properly.

Code Example of @DependsOn

Let’s take a look at the code:

@Component
@DependsOn("parameterInitializer")
public class CacheManager {

    private static final Logger log = LoggerFactory.getLogger(CacheManager.class);

    public CacheManager() {
        log.info("CacheManager initialized.");
    }
}

@Component("parameterInitializer")
public class ParameterInitializer {

    private static final Logger log = LoggerFactory.getLogger(ParameterInitializer.class);

    public ParameterInitializer() {
        log.info("ParameterInitializer initialized.");
    }
}


Expected Output

If you run the code, in the initialization logs you should see something like this:

2024-06-24T22:19:33.450-03:00  INFO 21436 --- [           main] c.s.m.dependson.ParameterInitializer     : ParameterInitializer initialized.
2024-06-24T22:19:33.451-03:00  INFO 21436 --- [           main] c.spring.mastery.dependson.CacheManager  : CacheManager initialized.


Conclusion

In this blog post, you learned about the @DependsOn annotation and how you can use it to set dependencies between beans that aren’t directly connected.

If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!

Willian Moya (@WillianFMoya) / X (twitter.com)

Willian Ferreira Moya | LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *