Implementing Basic Inversion of Control in Spring Framework
The Spring Framework functions as an open-source, lightweight infrastructure for enterprise Java development. Its architecture revolves around two primary concepts: Aspect-Oriented Programming (AOP) and Inversion of Control (IoC). AOP allows for modularizing cross-cutting concerns without alternig existing source code, while IoC shifts the responsibility of object creation and dependency management from the application code to the container.
As a comprehensive solution, Spring addresses various layers of the Java EE stack. The web layer typically utilizes Spring MVC, business logic relies on the IoC container, and data access often leverages modules like JdbcTemplate. Under the hood, the IoC container relies on XML configuration, parsed via libraries such as DOM4J, combined with the Factory design pattern and Java Reflection to instantiate and manage beans dynamically.
Configuration can be handled through XML definitions or annnotation-based scanning. The following example demonstrates setting up IoC using XML configuration.
Service Class Definition
Create a service component that will be managed by the container.
package com.example.spring.core;
public class AccountService {
public void deposit() {
System.out.println("Processing account deposit via Spring container");
}
}
Spring Configuration File
Define the bean metadata in an XML file located in the classpath.
<?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 the account service bean -->
<bean id="accountService" class="com.example.spring.core.AccountService"/>
</beans>
Verification Test
Use a test client to load the context and retrieve the managed instance.
package com.example.spring.core;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ContainerTest {
@Test
public void verifyIoCInjection() {
// Initialize the Spring container with XML config
ApplicationContext container =
new ClassPathXmlApplicationContext("application-context.xml");
// Retrieve the bean managed by Spring
AccountService service = (AccountService) container.getBean("accountService");
System.out.println(service);
service.deposit();
}
}
Ensure the necessary Spring core dependencies are included in the project build path to execute the context loading successfully.