
Spring Constructor Injection Inheriting Bean
The Spring, you can perform constructor injection for a bean that inherits from another bean. This means that you can have a child bean that receives its dependencies from a parent bean using constructor injection. This is useful when you want to configure common dependencies in a parent bean and reuse them in multiple child beans with specific customizations.
Here’s how to achieve constructor injection for a child bean inheriting from a parent bean:
1. Create a Parent Bean:
First, create a parent bean that defines common dependencies in its constructor. For example, let’s create a Person
class as the parent bean:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
// Getter and setter for 'name'
}
2. Configure the Parent Bean in XML:
In your Spring XML configuration file (e.g., applicationContext.xml
), define the parent bean and its dependencies:
<bean id="parentPerson" class="com.example.Person">
<constructor-arg value="CommonName" />
</bean>
In this configuration, we’ve created a bean named “parentPerson” of type com.example.Person
with a common name.
3. Create Child Beans:
Now, create child beans that inherit from the parent bean. You can create multiple child beans, each with its own customizations. Here’s an example of two child beans, “john” and “alice,” that inherit from the parent bean:
<bean id="john" parent="parentPerson">
<constructor-arg value="John" />
</bean>
<bean id="alice" parent="parentPerson">
<constructor-arg value="Alice" />
</bean>
In this configuration:
- We create a child bean named “john” that inherits from “parentPerson” and customizes the name to “John.”
- We create another child bean named “alice” that also inherits from “parentPerson” and customizes the name to “Alice.”
4. Access the Child Beans:
You can access the child beans, “john” and “alice,” by retrieving them from the Spring application context. Each child bean inherits the common dependency (name) from the parent bean but can have its own customized values.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Person john = context.getBean("john", Person.class);
Person alice = context.getBean("alice", Person.class);
System.out.println("John's name: " + john.getName()); // Output: John's name: John
System.out.println("Alice's name: " + alice.getName()); // Output: Alice's name: Alice
This approach allows you to define common dependencies in a parent bean and reuse them in multiple child beans, customizing only the necessary values in each child bean. It promotes code reuse and simplifies the configuration of similar beans with slight variations.