- What Is the Spring Container?
- What is Configuration Metadata?
- How to Create a Spring Container?
- How to Retrieve Beans from Spring Container?
- Create Spring IoC Container XML Config Example
- Create Spring IoC Container Java Config Example
What Is the Spring Container?
The Spring container is a core component of the Spring Framework. It is responsible for creating and managing the lifecycle and configuration of application objects (beans). The container reads configuration metadata to know how to instantiate, configure, and assemble these beans. This metadata can be supplied in various forms, such as XML, annotations, or Java code.
Responsibilities of the IoC Container
- Instantiating beans: Creating instances of the beans defined in the configuration.
- Wiring beans: Managing dependencies between beans.
- Configuring beans: Setting properties and managing initialization and destruction callbacks.
- Managing the bean lifecycle: Handling the complete lifecycle of a bean from creation to destruction.
Spring provides two main types of containers:
- BeanFactory: The simplest container providing basic dependency injection features.
- ApplicationContext: An enhanced container providing more enterprise-specific functionality such as event propagation, declarative mechanisms to create a bean, and various ways to look up.
The org.springframework.beans
and org.springframework.context
packages are fundamental to the Spring Framework’s IoC container.
How the Spring IoC Container Works
- Read Dependency and Configuration Metadata: The Spring IoC container reads configuration metadata, which can be supplied in XML, annotations, or Java-based configurations.
- Create Dependency Objects and Inject Them: Based on the configuration metadata, the container creates and injects dependencies into business objects (POJOs).
What is Configuration Metadata?
Configuration metadata is how you instruct the Spring container about the objects it should manage. It defines how beans are created, configured, and assembled within the Spring IoC container. There are three primary ways to provide configuration metadata to the Spring container:
- XML-based configuration: The traditional way to define beans and dependencies in XML files.
- Annotation-based configuration: Uses annotations in Java classes to define beans and their dependencies.
- Java-based configuration: Uses Java classes annotated with
@Configuration
and methods annotated with@Bean
to define beans and dependencies.
How to Create a Spring Container?
Spring provides various implementations of the ApplicationContext
interface, each suited for different scenarios. Here are the common ones:
- AnnotationConfigApplicationContext: Used for standalone Java applications with annotation-based configuration.
- ClassPathXmlApplicationContext: Used for standalone applications with XML configuration loaded from the classpath.
- FileSystemXmlApplicationContext: Similar to
ClassPathXmlApplicationContext
, but the XML configuration file can be loaded from anywhere in the file system. - AnnotationConfigWebApplicationContext: Used for web applications with annotation-based configuration.
- XmlWebApplicationContext: Used for web applications with XML configuration.
Example: Creating a Spring Container
Using XML Configuration:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Using Java Configuration:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
How to Retrieve Beans from Spring Container?
Both BeanFactory
and ApplicationContext
provide the getBean()
method to retrieve beans from the Spring container.
ApplicationContext getBean() Example
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
BeanFactory getBean() Example
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
Creating a Spring Container with XML Configuration
Step 1: Create a Maven Project
Add the necessary Spring 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>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
</project>
Step 2: Define Spring Beans in XML
Create an applicationContext.xml
file in the src/main/resources
directory:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="greetingService" class="net.javaguides.spring.ioc.GreetingService">
<property name="message" value="Hello, Spring XML Configuration!"/>
</bean>
</beans>
Step 3: Create a Java Class to Retrieve Beans
package net.javaguides.spring.ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
GreetingService greetingService = (GreetingService) context.getBean("greetingService");
greetingService.getMessage();
}
}
GreetingService.java:
package net.javaguides.spring.ioc;
public class GreetingService {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Message: " + message);
}
}
Creating a Spring Container with Java Configuration
Step 1: Create a Maven Project
Use the same Maven project setup as the XML example.
Step 2: Define Spring Beans in Java
Create an AppConfig.java
file:
package net.javaguides.spring.ioc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public GreetingService greetingService() {
GreetingService greetingService = new GreetingService();
greetingService.setMessage("Hello, Spring Java Configuration!");
return greetingService;
}
}
Step 3: Create a Java Class to Retrieve Beans
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);
GreetingService greetingService = (GreetingService) context.getBean("greetingService");
greetingService.getMessage();
((AnnotationConfigApplicationContext) context).close();
}
}
GreetingService.java:
package net.javaguides.spring.ioc;
public class GreetingService {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Message: " + message);
}
}
Summary
In this blog post, we covered the basics of the Spring IoC container, including how it works, what configuration metadata is, and how to create and retrieve beans from the container using both XML and Java-based configurations. This flexibility allows you to choose the most suitable configuration method for your project's needs. By understanding these concepts, you can effectively leverage the power of Spring to manage your application's dependencies and configurations.
Very nicely explained Spring IOC container.
ReplyDeleteClearly and useful !
ReplyDeleteCan you please explain the difference between bean factory and application context in detail.
ReplyDeleteSure. I have written separate article here at Difference Between the BeanFactory and ApplicationContext
DeleteUr contents r very helpful ...
ReplyDeletePlease make some videos on microservices and angular lastest for beginners