Inversion of Control (IoC) container

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2024-01-13 09:00:01 Viewed : 183


In Spring, the Inversion of Control (IoC) container is responsible for managing the lifecycle of Java objects, creating and wiring them together. The most commonly used IoC container in Spring is the ApplicationContext. Here is a simple example of using the Spring IoC container with XML configuration:

  1. Create a Java class:
java
public class HelloWorld { private String message; public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("Your Message: " + message); } }
  1. Create a Spring configuration file (applicationContext.xml):
xml
<?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"> <!-- Define a bean with the name "helloWorld" and specify its class --> <bean id="helloWorld" class="com.example.HelloWorld"> <!-- Set the "message" property value --> <property name="message" value="Hello, Spring IoC!"/> </bean> </beans>
  1. Create a main class to run the application:
java
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { // Load the Spring configuration file ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // Get the bean with the name "helloWorld" from the context HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); // Call a method on the bean obj.getMessage(); } }
  1. Run the application:

When you run the MainApp class, the Spring IoC container will read the applicationContext.xml file, create an instance of the HelloWorld class, set its message property, and then you can retrieve and use that bean.

This is a basic example, and Spring provides more advanced features like annotations (@Component, @Autowired, etc.) for configuring beans without XML, Java-based configuration, and more. The XML configuration is just one way to define beans; Spring supports various other methods for defining beans and managing dependencies.

Search
Sub-Categories
Related Articles

Leave a Comment: