In Spring, beans represent the core objects that are managed within the Spring IoC (Inversion of Control) container.
Below are the Spring Bean Life Cycle stages :-
Below are the types of Dependency Injection :-
Feature | Constructor Injection | Setter Injection |
---|---|---|
Definition | In Constructor Injection, dependencies are provided through the class constructor. | In Setter Injection, dependencies are injected through public setter methods after the object is created. |
When to Use | Best for mandatory dependencies, as these dependencies are required at the time of object creation. | Ideal for optional dependencies or cases where dependencies might need to be changed after the object has been created. |
Object Creation | Dependencies are provided at the time of object creation, making them mandatory. | Dependencies can be set or modified after the object is created. |
Testability | Good for testing as all dependencies are injected upfront, making it easy to provide mock dependencies. | Also testable, though less ideal for mandatory dependencies as it allows for later modifications. |
Circular Dependency Handling | Can create issues with circular dependencies, as all dependencies must be resolved at creation. | Handles circular dependencies more gracefully, as dependencies can be set post-creation. |
Immutability | Promotes immutability as dependencies are usually final after construction. | Allows mutable dependencies, as setters can be called to change dependencies later. |
There are 3 main ways to achieve DI in Spring :-
@Configuration
public class AppConfig
{
@Bean
public Engine engine()
{
return new Engine();
}
@Bean
public Car car(Engine engine)
{
return new Car(engine); // Constructor Injection
}
}
<constructor-arg>
tag to inject dependencies into the constructor.
<property>
tag to inject dependencies through setter methods.
<!-- Constructor Injection -->
<bean id="engine" class="com.example.Engine"/>
<bean id="car" class="com.example.Car">
<constructor-arg ref="engine"/>
</bean>
<!-- Setter Injection -->
<bean id="engine" class="com.example.Engine"/>
<bean id="car" class="com.example.Car">
<property name="engine" ref="engine"/>
</bean>
@Component
public class Car
{
private Engine engine;
@Autowired
public Car(Engine engine) // Constructor Injection
{
this.engine = engine;
}
}
@Component
public class engine
{
// Engine implementation
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.