New to Spring framework. I am experimenting around with injection. For that I have created some simple test classes.
Basically, I want that the variable num
in class2
should be injected with value 10
after method asd()
from class1
is executed.
My code is as following:
class1.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class class1 extends class2 {
public int num;
public void setMessage(int num) {
this.num = num;
}
public int getMessage() {
System.out.println("getnum: " + num);
return num;
}
public void asd() {
num = 10;
ApplicationContext context = new ClassPathXmlApplicationContext("test/Beans.xml");
test.class2 login2 = (test.class2) context.getBean("class2");
login2.disp();
}
}
class2.java
public class class2 {
public int num;
public void setNum(int num) {
System.out.println("setnum: " + num);
this.num = num;
}
public int getNum() {
return num;
}
public void disp() {
System.out.println("num: " + num);
}
}
main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class main {
public static void main(String args[]) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
test.class1 login = (test.class1) context.getBean("class1");
login.asd();
}
}
Beans.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-3.0.xsd">
<bean id="class2" class="test.class2" parent="class1" lazy-init="true" />
<bean id="class1" class="test.class1" />
</beans>
I am expecting the value of num
when the method asd()
is executed to be displayed as 10. But its giving 0
. Can anyone tell me what am I doing wrong? Even tried lazy-initializing it so it initializes after the value is set. But the result is still same...