Flat Preloader Icon

Constructor Injection with Dependent Object

  • Constructor injection in Spring allows you to inject dependencies into a class when it’s instantiated by providing those dependencies as arguments to the constructor. This is a useful technique when you have classes that depend on other objects or services.
  • When using constructor injection with dependent objects, you’re essentially creating a chain of dependencies, where one object depends on another, and so on. Here’s how to achieve constructor injection with dependent objects in Spring:
Suppose you have the following classes:
				
					public class Engine {
    public Engine() {
        // Constructor logic for Engine
    }

    public void start() {
        System.out.println("Engine started");
    }
}

public class Car {
    private final Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        engine.start();
        System.out.println
        ("Car started");
    }
}

				
			
  • In this example, Car depends on an Engine, and you want to inject the Engine into the Car via constructor injection. Here’s how you can configure and use constructor injection in Spring:

Define Beans in Spring Configuration:

  • In your Spring configuration (either XML-based or Java-based), define the beans for both Car and Engine:
  • XML-based configuration:
				
					<bean id="engine" class=
"com.example.Engine" />
<bean id="car" class=
"com.example.Car">
<constructor-arg ref="engine" />
</bean>

				
			
  • Java-based configuration:
				
					@Configuration
public class AppConfig {
    @Bean
    public Engine engine() {
        return new Engine();
    }

    @Bean
    public Car car() {
        return new Car(engine());
    }
}

				
			

Use the Spring ApplicationContext:

  • In your application code, obtain an instance of the Spring ApplicationContext using your configuration:
				
					public class MainApplication {
public static void main(String[] args)
{
        ApplicationContext context
= new 
AnnotationConfigApplicationContext
        (AppConfig.class);

Car car = context.getBean(Car.class);
        car.start();
    }
}

				
			
  • In this code, when you retrieve the Car bean from the ApplicationContext, Spring automatically injects the Engine bean into the Car constructor.

Run the Application:

  • When you run the application, it will output:
				
					Engine started
Car started

				
			
  • This demonstrates that the Car object has its dependency (Engine) injected via constructor injection, and you can use the Car object as expected.
  • Constructor injection with dependent objects is a clean and effective way to manage dependencies and ensure that all required components are properly initialized before use. It promotes loose coupling between components and simplifies testing by making it easy to provide mock or test instances of dependencies when needed.