I have just started reading "Spring In Action - Third edition" and am stuck up while experimenting with wiring concepts. I am unable to understand the lifecycle of a bean after writing this code :
public class TestCase {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
Test1 t1 = (Test1)context.getBean("test1");
t1.setName1("Win");
Test1 t2 = (Test1)context.getBean("test1");
t2.setName1("Lin");
Test2 t3 = (Test2)context.getBean("test2");
Test1 t4 = t3.getName();
System.out.println("End" +t4.getName1());
}
}
public class Test1 {
private String name1;
public String getName1() {
System.out.println("test1 - getter");
return name1;
}
public void setName1(String name1) {
System.out.println("test1 - setter");
this.name1 = name1;
}
public void onStart()
{
System.out.println("start1");
}
public void onStop()
{
System.out.println("stop1");
}
}
public class Test2 {
private int age;
private Test1 name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Test1 getName() {
System.out.println("test2 - getter");
return name;
}
public void setName(Test1 name) {
System.out.println("test2 - setter");
this.name = name;
}
public void onStart()
{
System.out.println("start2");
}
public void onStop()
{
System.out.println("stop2");
}
}
我在此检验:
<bean id="test1" class="springidol.Test1" init-method="onStart" destroy-method="onStop" >
</bean>
<bean id="test2" class="springidol.Test2" init-method="onStart" destroy-method="onStop">
<property name="name" ref="test1"></property>
</bean>
产出如下:
start1
test2 - setter
start2
test1 - setter
test1 - setter
test2 - getter
test1 - getter
End - Lin
如果我把测试1的范围改为原型一:
start1
test2 - setter
start2
start1
test1 - setter
start1
test1 - setter
test2 - getter
test1 - getter
End - null
我知道,我要求的是太多的,但有人可以让我了解这里所涉及的步骤——我不明白,为什么在装货头1之后(甚至在装装货2之前)就要求测试2组。
Secondly, why are the "End" outputs for prototype and default scopes different ? Thanks.