Spring - @DependsOn Annotation Example

In this article, we will discuss how to use @DependsOn annotation in Spring Applications with an example.
The @DependsOn annotation can force Spring IoC container to initialize one or more beans before the bean which is annotated by @DependsOn annotation.
The @DependsOn annotation may be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.
The following example shows how to use @DependsOn annotation in a spring application.

Spring @DependsOn annotation example

Let's create an example to demonstrates usage of use @DependsOn annotation in a spring application.

Tools and technologies used

  • Spring Framework - 5.1.0.RELEASE
  • JDK - 8 or later
  • Maven - 3.2+
  • IDE - Eclipse Mars/STS

Create a Simple Maven Project

Create a simple maven project using your favorite IDE and refer below section for packaging structure. If you are new to maven then read this article How to Create a Simple Maven Project.

Project Structure

Below diagram shows a project structure for your reference -

The pom.xml File

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.spring</groupId>
    <artifactId>spring-dependson-annotation</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>spring-scope-example</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.1.0.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
     <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
         </plugins>
    </build>
</project>

Create Spring Beans - FirstBean, SecondBean, and ThirdBean

FirstBean.java
package net.javaguides.spring.dependson;

import org.springframework.beans.factory.annotation.Autowired;

public class FirstBean {

    @Autowired
    private SecondBean secondBean;

    @Autowired
    private ThirdBean thirdBean;

    public FirstBean() {
        System.out.println("FirstBean Initialized via Constuctor");
    }

    public void populateBeans() {
        secondBean.display();
        thirdBean.display();
    }
}
SecondBean.java
package net.javaguides.spring.dependson;

public class SecondBean {
    public SecondBean() {
        System.out.println("SecondBean Initialized via Constuctor");
    }

    public void display() {
        System.out.println("SecondBean method called");
    }
}
ThirdBean.java
package net.javaguides.spring.dependson;

public class ThirdBean {
    public ThirdBean() {
        System.out.println("ThirdBean Initialized via Constuctor");
    }

    public void display() {
        System.out.println("ThirdBean method called");
    }
}

Java Based Configuration - AppConfig.java

Declare the above beans in java based configuration class.
AppConfig.java
package net.javaguides.spring.dependson;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class AppConfig {

    @Bean("firstBean")
    @DependsOn(value = {
        "secondBean",
        "thirdBean"
    })
    public FirstBean firstBean() {
        return new FirstBean();
    }

    @Bean("secondBean")
    public SecondBean secondBean() {
        return new SecondBean();
    }

    @Bean("thirdBean")
    public ThirdBean thirdBean() {
        return new ThirdBean();
    }
}

Running Spring Application - Application.java

Let's create a main class and run an application.
package net.javaguides.spring.dependson;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        FirstBean bean = context.getBean(FirstBean.class);
        bean.populateBeans();
        context.close();
    }
}

Output

SecondBean Initialized via Constuctor
ThirdBean Initialized via Constuctor
FirstBean Initialized via Constuctor
SecondBean method called
ThirdBean method called
As you can see in the above output, the beans SecondBean and ThirdBean are initialized before bean FirstBean.
If you remove the @DependsOn annotation from firstBean() method of AppConfig class, the output (i.e. an order of initialization of beans) of the main class will be different on each run like:
FirstBean Initialized via Constuctor
SecondBean Initialized via Constuctor
ThirdBean Initialized via Constuctor
SecondBean method called
ThirdBean method called
The source code of this article is available on my GitHub repository https://github.com/RameshMF/spring-core-tutorial

Spring is an Integration Framework for developing Enterprise Applications easily.
Spring is an Open Source framework, developed by Rod Johnson.


Spring's Pledge :
J2EE should be Easy to Use
Spring framework simplifies the complexity of enterprise applications because it uses Java beans to implement enterprise applications that were previously possible only with enterprise beans.
The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so application developer can focus on your application.
As an application developer how can I benefit from the Spring platform:
  • Make a Java method execute in a database transaction without having to deal with transaction APIs.
  • Make a local Java method an HTTP endpoint without having to deal with the Servlet API.
  • Make a local Java method a message handler without having to deal with the JMS API.
  • Make a local Java method a management operation without having to deal with the JMX API.

Benefits of Spring Framework

Here are advantages of Spring Framework: 
1. Solving difficulties of Enterprise application development: Spring is solving the difficulties of development of complex applications, it provides Spring Core, Spring IoC and Spring AOP for integrating various components of business applications.
2. Support Enterprise application development through POJOs:  Spring supports the development of Enterprise application development using the POJO classes which removes the need for importing heavy Enterprise container during development. This makes application testing much easier.
3. Easy integration of other frameworks:  Spring designed to be used with all other frameworks of Java, you can use ORM, Struts, Hibernate and other frameworks of Java together. Spring framework does not impose any restriction on the frameworks to be used together.
4. Application Testing:  Spring Container can be used to develop and run test cases outside enterprise container which makes testing much easier.
5. Modularity: Spring framework is a modular framework and it comes with many modules such as Spring MVC, Spring ORM, Spring JDBC, Spring Transactions etc. which can use as per application requirement in a modular fashion.
6. Spring Transaction Management: Spring Transaction Management interface is very flexible it can configure to use local transactions in the small application which can be scaled to JTA for global transactions.

Spring Modules Overview

The Spring Framework consists of features organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test.
Spring modules explained via below diagram :

1. Core Container


The Core Container consists of the
  • spring-core
  • spring-beans
  • spring-context, spring-context-support
  • spring-expression (Spring Expression Language)
  1. The spring-core and spring-beans modules provide the fundamental parts of the framework, including the IoC and Dependency Injection features.
  2. The Context (spring-context) module builds on the solid base provided by the Core and Beans modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry.
  3. spring-context-support provides support for integrating common third-party libraries into a Spring application context, in particular for caching (EhCache, JCache) and scheduling (CommonJ, Quartz).
  4. The spring-expression module provides a powerful Expression Language for querying and manipulating an object graph at runtime. It is an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification.

2. Spring AOP Module

Spring AOP separates business logic from system services such as logging, Transaction management, Persistence, Application resources(e.g: connection pooling). 
The spring-aop module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated
The separate spring-aspects module provides integration with AspectJ.

3. Messaging

Spring Framework 4 includes a spring-messaging module with key abstractions from the Spring Integration project such as Message, MessageChannel, MessageHandler, and others to serve as a foundation for messaging-based applications. The module also includes a set of annotations for mapping messages to methods, similar to the Spring MVC annotation based programming model.

4. Data Access/Integration


The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS, and Transaction modules.
The spring-jdbc module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.
The spring-tx module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs (Plain Old Java Objects).
The spring-orm module provides integration layers for popular object-relational mapping APIs, including JPA and Hibernate. Using the spring-orm module you can use these O/R-mapping frameworks in combination with all of the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.
The spring-oxm module provides an abstraction layer that supports Object/XML mapping implementations such as JAXB, Castor, JiBX and XStream.
The spring-jms module (Java Messaging Service) contains features for producing and consuming messages. Since Spring Framework 4.1, it provides integration with the spring-messaging module.

5. Web


The Web layer consists of the spring-web, spring-webmvc and spring-websocket modules.

The spring-web module provides basic web-oriented integration features such as multipart file upload functionality and the initialization of the IoC container using Servlet listeners and a web-oriented application context. It also contains an HTTP client and the web-related parts of Spring’s remoting support.


The spring-webmvc module (also known as the Web-Servlet module) contains Spring’s model-view-controller (MVC) and REST Web Services implementation for web applications. Spring’s MVC framework provides a clean separation between domain model code and web forms and integrates with all of the other features of the Spring Framework.

6. Test


The spring-test module supports the unit testing and integration testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that you can use to test your code in isolation.

Comments