Thursday, May 31, 2012

Spring Framework- Autowiring with "constructor"


Here discuss that how to configure autowiring of bean with the constructor-
Directory structure of project-

Class Tri.java
package com.test;

public class Tri {
Point p;
public Tri(Point p)
{
this.p=p;
}
public Point getP() {
return p;
}
public void setP(Point p) {
this.p = p;
}
public void show()
{
System.out.println("x="+p.getX());
System.out.println("y="+p.getY());
}
}
Class Point.java
package com.test;

public class Point {
int x,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;
}
}
Class Draw.java
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Draw {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Tri t=(Tri) context.getBean("tri");
t.show();
}
}

Spring.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="p" class="com.test.Point">
<property name="x" value="10"></property>
<property name="y" value="20"></property>
 </bean>
<bean id="tri" class="com.test.Tri" autowire="constructor">
</bean>
</beans>

Output is-

x=10
y=20


For Further Reading,
General, Java, spring

0 comments:

Post a Comment


 

Site Status

Man Behind Technical Today

Hello, I am Navin Bansal. I am a student of MCA in Rajsthan Institute of Engineering and Technology and owner of this blog. I share my view and ideas among people.