Constructor Injection with Dependent Object

This article contains detailed description with example on “Constructor Injection with Dependent Object” topic.

Whenever we have HAS-A relationship between the classes, instance of dependent object comes into the picture. We create the instance of dependent object (contained object) first then pass it as an argument of the main class constructor.

In this example we will discuss about constructor injection with dependent object using a simple and self explanatory program.

This class contains three properties, one constructor and toString() method to return the values of these object.

Address.java
Students.java

It contains three properties id, name and address(dependent object) ,constructors and show() method to show the records of the current object including the depedent object.

applicationContext.xml

The ref attribute is used to define the reference of another object, such way we are passing the dependent object as an constructor argument.

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.

Output

ID:10 Name:Smith City:Pune State:Maharashtra Country:India
It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *