Backend Development 18 min read

Understanding Dependency Injection in Spring: Concepts, Configuration Methods, and Code Samples

This article explains the fundamentals of dependency and dependency injection in Spring, compares class relationships such as inheritance, association, aggregation, and composition, and demonstrates constructor, static‑factory, instance‑factory, setter, constant, and ID reference injection with detailed XML configurations and Java code examples.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Understanding Dependency Injection in Spring: Concepts, Configuration Methods, and Code Samples

In traditional application design, dependencies refer to relationships between classes; this article reviews class relationships including generalization (inheritance), implementation, dependency (a usage relationship without ownership), association (ownership via instance variables), aggregation (weak whole‑part), and composition (strong whole‑part).

Spring IoC introduces two layers of dependency: the Bean depends on the container (the container creates and manages the Bean) and the container injects resources (other Beans, files, constants) into the Bean, mirroring traditional class relationships.

Applying dependency injection (DI) brings several benefits: dynamic replacement of Bean dependencies without source changes, clearer interface‑driven programming, promotion of object composition over inheritance, increased Bean reusability, reduced coupling, and cleaner code structure.

Constructor Injection is performed by specifying constructor arguments in the XML configuration. It can be based on index, type, or name (the latter requiring debug information or @ConstructorProperties). Example Bean class:

package cn.javass.spring.chapter3.helloworld;
public class HelloImpl3 implements HelloApi {
    private String message;
    private int index;
    // @java.beans.ConstructorProperties({"message", "index"})
    public HelloImpl3(String message, int index) {
        this.message = message;
        this.index = index;
    }
    @Override
    public void sayHello() {
        System.out.println(index + ":" + message);
    }
}

XML configurations for the three constructor‑injection styles:

<!-- by index -->
<bean id="byIndex" class="cn.javass.spring.chapter3.HelloImpl3">
    <constructor-arg index="0" value="Hello World!"/>
    <constructor-arg index="1" value="1"/>
</bean>

<!-- by type -->
<bean id="byType" class="cn.javass.spring.chapter3.HelloImpl3">
    <constructor-arg type="java.lang.String" value="Hello World!"/>
    <constructor-arg type="int" value="2"/>
</bean>

<!-- by name -->
<bean id="byName" class="cn.javass.spring.chapter3.HelloImpl3">
    <constructor-arg name="message" value="Hello World!"/>
    <constructor-arg name="index" value="3"/>
</bean>

Testing the configuration uses a simple JUnit test that loads the XML file and retrieves each Bean by its id, invoking sayHello() to verify correct injection.

Static‑Factory and Instance‑Factory Injection use the same XML syntax but specify a factory method. Example static‑factory class:

package cn.javass.spring.chapter3;
import cn.javass.spring.chapter2.helloworld.HelloApi;
public class DependencyInjectByStaticFactory {
    public static HelloApi newInstance(String message, int index) {
        return new HelloImpl3(message, index);
    }
}

Corresponding bean definitions:

<bean id="byIndex" class="cn.javass.spring.chapter3.DependencyInjectByStaticFactory" factory-method="newInstance">
    <constructor-arg index="0" value="Hello World!"/>
    <constructor-arg index="1" value="1"/>
</bean>
... (similar definitions for byType and byName)

Instance‑factory injection follows the same pattern, defining a non‑static factory bean and referencing it with factory-bean and factory-method .

Setter Injection injects dependencies via JavaBean setter methods after the Bean is instantiated. Example Bean with setters:

package cn.javass.spring.chapter3;
import cn.javass.spring.chapter2.helloworld.HelloApi;
public class HelloImpl4 implements HelloApi {
    private String message;
    private int index;
    public void setMessage(String message) { this.message = message; }
    public void setIndex(int index) { this.index = index; }
    @Override
    public void sayHello() { System.out.println(index + ":" + message); }
}

XML configuration:

<bean id="bean" class="cn.javass.spring.chapter3.HelloImpl4">
    <property name="message" value="Hello World!"/>
    <property name="index"><value>1</value></property>
</bean>

Setter injection follows JavaBean conventions: a public no‑arg constructor, private fields, and public setXxx methods.

Constant Injection injects simple values directly using value attributes or nested <value> elements. Spring automatically converts string literals to the required property type, handling booleans with tolerant values such as on/off , yes/no , or 1/0 .

Bean ID Injection injects a Bean's identifier as a constant string using <idref> . Two forms exist: <idref bean="..."/> validates existence at container startup, while <idref local="..."/> validates during XML parsing.

<property name="id"><idref bean="bean1"/></property>
<property name="id"><idref local="bean2"/></property>

Example Bean class for ID reference:

package cn.javass.spring.chapter3.bean;
public class IdRefTestBean {
    private String id;
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
}

Overall, the article demonstrates how Spring’s IoC container supports various injection techniques, enabling flexible, decoupled, and maintainable Java applications.

JavaIoCSpringdependency injectionConstructor InjectionSetter InjectionBean Configuration
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.