Spring Framework IoC and Dependency Injection: Configuration, Bean Management, and Annotation‑Based Development
This article introduces the lightweight Spring framework, explains the concepts of IoC and AOP, demonstrates how to configure beans using XML and annotations, and provides detailed code examples for object creation, property injection, complex type injection, and annotation‑driven bean management in Java.
Spring is a lightweight Java EE framework that can run without a container, unlike heavyweight frameworks such as EJB. Its core ideas are IoC (Inversion of Control) and AOP (Aspect‑Oriented Programming), which allow the container to create and assemble objects and to execute additional code before or after certain methods.
IoC Operations
Object creation is delegated to Spring. IoC can be configured via XML files or annotations.
IoC Introductory Example
1. Import the required Spring Core JARs and logging libraries. 2. Create a simple Java class com.wm103.ioc.User with an add() method.
package com.wm103.ioc;
public class User {
public void add() {
System.out.println("add...");
}
}3. Create the Spring configuration file bean1.xml (or applicationContext.xml) to define the bean:
<?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="user" class="com.wm103.ioc.User"/>
</beans>4. Write a JUnit test to load the context and obtain the bean:
package com.wm103.ioc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoC {
@Test
public void testUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user = (User) context.getBean("user");
System.out.println(user);
user.add();
}
}Bean Instantiation Methods
Spring supports three ways to instantiate beans:
Using a no‑argument constructor: <bean id="user" class="com.wm103.ioc.User"/> Using a static factory method:
<bean id="user" class="com.wm103.ioc.UserFactory" factory-method="createInstance"/>Using an instance factory method (requires a separate factory bean):
<bean id="userFactory" class="com.wm103.ioc.UserFactory"/>
<bean id="user" factory-bean="userFactory" factory-method="createInstance"/>Common Bean Attributes id: bean name (no special characters). class: fully qualified class name. scope: singleton (default) or prototype, request, session, globalSession.
Property Injection
Properties can be injected via setter methods or constructor arguments. Example using a constructor‑arg:
<bean id="demo1" class="com.wm103.ioc.Demo1">
<constructor-arg name="demoName" value="Demo1"/>
</bean>Example using a setter:
<bean id="demo2" class="com.wm103.ioc.Demo2">
<property name="demoName" value="Demo2"/>
</bean>Injecting Object‑Type Properties
Complex types such as arrays, List, Map, and Properties can be injected. The following bean PropertyDemo demonstrates all of them:
package com.wm103.ioc;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class PropertyDemo {
private String[] arrs;
private List<String> list;
private Map<String, String> map;
private Properties properties;
// setters and getters omitted for brevity
}Corresponding XML configuration:
<bean id="pdemo" class="com.wm103.ioc.PropertyDemo">
<property name="arrs">
<list>
<value>value 1 of array</value>
<value>value 2 of array</value>
<value>value 3 of array</value>
</list>
</property>
<property name="list">
<list>
<value>value 1 of list</value>
<value>value 2 of list</value>
<value>value 3 of list</value>
</list>
</property>
<property name="map">
<map>
<entry key="key1" value="value 1 of map"/>
<entry key="key2" value="value 2 of map"/>
<entry key="key3" value="value 3 of map"/>
</map>
</property>
<property name="properties">
<props>
<prop key="username">root</prop>
<prop key="password">123</prop>
</props>
</property>
</bean>IoC vs DI
IoC (Inversion of Control) delegates object creation to the Spring container, while DI (Dependency Injection) supplies values to object properties. DI relies on IoC as its foundation.
Annotation‑Based Bean Management
Annotations such as @Component, @Service, @Repository, and @Controller can be used to declare beans directly in code. Example:
package com.wm103.anno;
import org.springframework.stereotype.Component;
@Component(value="user")
public class User {
public void add() {
System.out.println("User Add...");
}
}Enable annotation scanning in bean1.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.wm103"/>
</beans>Injecting dependencies with annotations can be done using @Autowired or @Resource:
package com.wm103.anno;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service(value="userService")
public class UserService {
@Resource(name="userDao")
private UserDao userDao;
public void add() {
System.out.println("UserService Add...");
userDao.add();
}
}Testing the annotation configuration:
package com.wm103.anno;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAnno {
@Test
public void testUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user = (User) context.getBean("user");
user.add();
}
}In practice, XML configuration is often used for object creation, while annotations are preferred for property injection, providing a flexible hybrid approach.
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 Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.
