Automating Dependency Injection with Spring Bean Auto-Wiring
Explicit dependency injection via <property> elements requires manual mapping betweeen component instances and target attributes. Spring's Inversion of Control container offers an alternative approach through automatic wiring, which resolves and populates references without verbose XML definitions, significantly reducing configuration overhead.
Component Definisions
The following entities demonstrate a hierarchical relationship where a role depends on a structural unit:
package com.example.di;
public class Division {
// Represents an organizational unit
}
package com.example.di;
public class StaffMember {
private Division departmentRef;
public StaffMember() {}
public StaffMember(Division departmentRef) {
this.departmentRef = departmentRef;
}
public Division getDepartmentRef() {
return departmentRef;
}
public void setDepartmentRef(Division departmentRef) {
this.departmentRef = departmentRef;
}
@Override
public String toString() {
return "StaffMember{departmentRef=" + departmentRef + "}";
}
}
Configuration Strategy
The <bean> declaration accepts an autowire attribute to activate resolution patterns. The container processes these strategies as follows:
byName: Aligns the target property name with corresponding bean identiifers in the registry.byType: Injects components based on declared types, requiring a unique candidate within the application context.
<?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">
<!-- Identifier must match the property name for 'byName' strategy -->
<bean id="departmentRef" class="com.example.di.Division"/>
<!-- Activates automatic population of the 'departmentRef' field -->
<bean id="engineerBean" class="com.example.di.StaffMember" autowire="byName"/>
</beans>
Verification Test
Execute the context loader to validate that the container successfully resolves and injects the dependency:
package com.example.test;
import com.example.di.StaffMember;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class WiringVerification {
@Test
public void verifyAutoInjectedDependency() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
StaffMember member = ctx.getBean("engineerBean", StaffMember.class);
System.out.println(member);
ctx.close();
}
}