Spring ApplicationContext Example

The ApplicationContext is the central interface within a Spring application for providing configuration information to the application. It includes all the functionalities of the BeanFactory interface and adds more enterprise-specific functionalities. The ApplicationContext interface provides the getBean() method to retrieve beans from the Spring container.

Features of ApplicationContext

  • Bean instantiation/wiring
  • Automatic BeanPostProcessor registration
  • Automatic BeanFactoryPostProcessor registration
  • Convenient MessageSource access (for internationalization)
  • Application event publication

The ApplicationContext interface uses eager loading, meaning all beans are instantiated when the ApplicationContext is started up.

ApplicationContext Interface Implementations

Spring provides several implementations of the ApplicationContext interface:

  1. AnnotationConfigApplicationContext: Used for standalone Java applications that use annotations for configuration.
  2. ClassPathXmlApplicationContext: Loads the bean configuration XML file from the classpath.
  3. FileSystemXmlApplicationContext: Loads the bean configuration XML file from anywhere in the file system.
  4. AnnotationConfigWebApplicationContext and XmlWebApplicationContext: Used for web applications.

ApplicationContext Example with Java-Based Configuration

Let's write code to create a Spring container using the ApplicationContext interface with Java-based configuration.

Step 1: Create a Simple Maven Project

Create a simple Maven project using your favorite IDE. Refer to the diagram below for the packaging structure. If you are new to Maven, read this article.

Project Structure

Step 2: Add Maven Dependencies

Add the following dependencies to your 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-ioc-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.5</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3: Configure HelloWorld Spring Beans

What Is a Spring Bean?

A Spring bean is a Java object that is managed by the Spring container. Here is a simple example of a HelloWorld Spring bean:

package net.javaguides.spring.ioc;

public class HelloWorld {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("My Message: " + message);
    }
}

Configuration Metadata - Configure HelloWorld Spring Beans

Define the HelloWorld bean using Java-based configuration:

package net.javaguides.spring.ioc;

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

@Configuration
public class AppConfig {

    @Bean
    public HelloWorld helloWorld() {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.setMessage("Hello World!");
        return helloWorld;
    }
}

Step 4: Create a Spring Container

Use AnnotationConfigApplicationContext to create the Spring container and load the Java-based configuration class:

package net.javaguides.spring.ioc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    }
}

Step 5: Retrieve Beans from the Spring Container

Retrieve and use the HelloWorld bean from the Spring container:

package net.javaguides.spring.ioc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        HelloWorld obj = context.getBean(HelloWorld.class);
        obj.getMessage();
    }
}

Output

My Message: Hello World!

Conclusion

The ApplicationContext interface is a powerful and flexible part of the Spring IoC container. It extends the basic functionalities of BeanFactory and provides advanced features such as internationalization, event propagation, and resource management. Understanding the responsibilities and capabilities of ApplicationContext is crucial for effectively managing and configuring your Spring applications. Using Java-based configuration provides a type-safe and modern way to configure Spring beans, enhancing readability and maintainability of your code.

Comments