Spring Injection Using Setter and Constructor.

Step1-write the Main class

Ioc.java

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

public class Ioc {
public static void main(String as[])
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("java4u.xml");

A a=(A)ctx.getBean("aObj");
a.showAll();
Hello he=(Hello)ctx.getBean("hello");
he.show();
Hai ha=(Hai)ctx.getBean("hai");
ha.show();

}
}

Step2- Hello.java

public class Hello {
private int x;
private String str;
Hello()
{
System.out.println("Hello-D.C");
}
public void setX(int x)
{
this.x=x;
}
public void setStr(String str)
{
this.str=str;
}
void show(){
System.out.println(x);
System.out.println(str);
}
}

Step3- Hai.java

public class Hai {
private int a;
private String msg;
public Hai()
{
System.out.println("Hai-D.C");
}
public Hai(int a,String msg)
{
System.out.println("Hai-2 arg con...");
this.a=a;
this.msg=msg;
}
void show()
{
System.out.println(a);
System.out.println(msg);
}

}

Step4-   A.java

public class A {
private Hello hello;
private Hai hai;

public A(Hello hello)
{
System.out.println("A-1 arg con...");
this.hello=hello;
}
public void setHai(Hai hai)
{
System.out.println("setHai");
this.hai=hai;
}
void showAll()
{
System.out.println("showAll()");
hello.show();
hai.show();
}
}

Step5-  Java4u.xml

src--New--Other--Xml--Xml
<?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-2.5.xsd">

<bean id="aObj" class="com.spring.A">
<constructor-arg ref="hello"/>
<property name="hai" ref="hai"/>
</bean>

<bean id="hello" class="com.spring.Hello" lazy-init="true">
<property name="x" value="100"/>
<property name="str">
<value>Hello Guys</value>
</property></bean>

<bean id="hai" class="com.spring.Hai">
<constructor-arg value="200"/>
<constructor-arg>
<value>Hai Guys</value>
</constructor-arg></bean>

</beans>


OutPut----


log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.


Hello-D.C
A-1 arg con...
Hai-2 arg con...
setHai
showAll()
100
Hello Guys
200
Hai Guys
100
Hello Guys
200
Hai Guys


0 comments :

Post a Comment