Master Spring IoC: From Bean Creation to Dependency Injection
This tutorial explains the concept of Inversion of Control in Spring, demonstrates how to configure beans with XML, compares BeanFactory and ApplicationContext, explores bean scopes and lifecycle, and provides detailed examples of constructor, static‑factory, instance‑factory, and collection injection techniques.
What Is IoC?
Inversion of Control (IoC) is a design principle where object creation and dependency management are delegated to the Spring container instead of being handled manually in code.
Spring implements IoC through Dependency Injection (DI), automatically wiring beans based on configuration.
Basic Bean Creation
Start with a Maven project and add the Spring context dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>Create a simple bean class:
public class User {
private String name;
private Integer age;
public User() {
System.out.println("Object created");
}
@Override
public String toString() {
return "User{name='" + name + "', age=" + age + "}";
}
}Define the bean in applicationContext.xml:
<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="user" class="com.example.spring.bean.User"/>
</beans>Load the context and retrieve the bean:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) ctx.getBean("user");
System.out.println(user);BeanFactory vs. ApplicationContext
BeanFactory loads beans lazily; objects are created only when getBean is called. ApplicationContext eagerly instantiates singleton beans during container startup and provides additional features such as internationalization and event propagation.
Bean Scopes
Spring supports five scopes:
singleton – one shared instance (default)
prototype – a new instance each request
request – one per HTTP request (web only)
session – one per HTTP session (web only)
global-session – one per global session (portlet only)
Example of a prototype bean:
<bean id="user" class="com.example.spring.bean.User" scope="prototype"/>Bean Lifecycle
Singleton beans are created when the container starts and destroyed when the container shuts down. Prototype beans are created on demand and garbage‑collected when no longer referenced.
Define init and destroy methods:
<bean id="user" class="com.example.spring.bean.User" init-method="init" destroy-method="destroy"/>Corresponding Java methods:
public void init() { System.out.println("Object initialized"); }
public void destroy() { System.out.println("Object destroyed"); }Creating Beans in Different Ways
Three creation strategies are supported:
Constructor injection
Static‑factory method
Instance‑factory method
Constructor injection example (already shown). Static‑factory example:
public class MyStaticBeanFactory {
public static User getBean() { return new User(); }
}XML configuration:
<bean id="user" class="com.example.spring.bean.MyStaticBeanFactory" factory-method="getBean"/>Instance‑factory example:
public class MyBeanFactory {
public User getBean() { return new User(); }
}XML configuration:
<bean id="myBeanFactory" class="com.example.spring.bean.MyBeanFactory"/>
<bean id="user" factory-bean="myBeanFactory" factory-method="getBean"/>Dependency Injection Techniques
Spring provides three DI methods:
Constructor injection
Setter (setXXX) injection
Annotation‑based injection (covered later)
Constructor injection with arguments:
<bean id="user" class="com.example.spring.bean.User">
<constructor-arg index="0" value="zhangsan"/>
<constructor-arg index="1" value="30"/>
</bean>Using name attribute for clarity:
<bean id="user" class="com.example.spring.bean.User">
<constructor-arg name="name" value="zhangsan"/>
<constructor-arg name="age" value="30"/>
</bean>Setter injection via property tags:
<bean id="user" class="com.example.spring.bean.User">
<property name="name" value="zhangsan"/>
<property name="age" value="30"/>
</bean>Injecting Collections
Spring can inject arrays, lists, sets, maps, and properties using property with nested collection tags.
<bean id="user" class="com.example.spring.bean.User">
<property name="array">
<list>
<value>zhangsan</value>
<value>lisi</value>
<value>wangwu</value>
</list>
</property>
<property name="list">
<list>
<value>zhangsan</value>
<value>lisi</value>
<value>wangwu</value>
</list>
</property>
<property name="set">
<set>
<value>zhangsan</value>
<value>lisi</value>
<value>wangwu</value>
</set>
</property>
<property name="map">
<map>
<entry key="001" value="zhangsan"/>
<entry key="002" value="lisi"/>
<entry key="003" value="wangwu"/>
</map>
</property>
<property name="prop">
<props>
<prop key="001">zhangsan</prop>
<prop key="002">lisi</prop>
<prop key="003">wangwu</prop>
</props>
</property>
</bean>Collections can be injected interchangeably; for example, an array property can use a list element.
Putting It All Together
By defining beans, scopes, lifecycle callbacks, and injection strategies in XML, developers can let Spring manage object creation and wiring, dramatically reducing manual coupling and boilerplate code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
