Dependency injection with dependent object

Let’s say we have a Triangle object and Triangle has three point.
So Triangle object dependent on Point object.
Let’s understand it with Example
Project Structure

Point.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
package com.spy.Triangle;
 
public class Point 
{
 
	private int x;
	private int y;
 
 
	public int getX() 
	{
		return x;
	}
	public void setX(int x) 
	{
		this.x = x;
	}
	public int getY() 
	{
		return y;
	}
	public void setY(int y) 
	{
		this.y = y;
	}
}

Triangle.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 
package com.spy.Triangle;
 
import java.util.List;
 
public class Triangle 
{
 
	List<Point> points;
 
	public List<Point> getPoints() 
	{
		return points;
	}
 
 
	public void setPoints(List<Point> points) 
	{
		this.points = points;
	}
 
	public void draw()
	{
		for(Point point:points)
		{
 
		System.out.println("point "+"("+point.getX()+","+point.getY()+")");
 
 
		}		
	}
 
}

spring2.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
<?xml version="1.0" encoding="UTF-8"?>
 
  <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 
    <bean id="triangle" class="com.spy.Triangle.Triangle">
 
    <property name="points">
 
    <list>
    <ref bean="point1"/>
    <ref bean="point2"/>
    <ref bean="point3"/>
    </list>
 
    </property>
 
    </bean>
 
   <bean id="point1" class="com.spy.Triangle.Point">
    <property name="x" value="0"></property>
    <property name="y" value="0"></property>
   </bean>    
 
   <bean id="point2" class="com.spy.Triangle.Point">  
    <property name="x" value="-12"></property>
    <property name="y" value="0"></property>
   </bean>    
 
   <bean id="point3" class="com.spy.Triangle.Point">
    <property name="x" value="12"></property>
    <property name="y" value="0"></property>
   </bean> 
 
   </beans>

Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
package com.spy.Triangle;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Test 
{
	public static void main(String[] args) 
	{
		ApplicationContext context=new ClassPathXmlApplicationContext("spring2.xml");
	               Triangle t=(Triangle)context.getBean("triangle");
		t.draw();
	}
}

Output

Leave a Reply

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