我有如下3个类,分别是Soldier、Gun和Bullet,可是getBean()之后Spring返回给我的不是一个完成了属性注入的soldier,请问何解?
Soldier:
[code="java"]
public class Soldier {
private Gun gun = null;
public Soldier() {
System.out.println("Inside soldier's constructor: soldier is here, gun is ready? - " + String.valueOf(this.gun != null));
}
public Gun getGun() {
return this.gun;
}
public void setGun(Gun arg_gun) {
this.gun = arg_gun;
}
public static void main(String arg[]) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
Soldier soldier = (Soldier)ac.getBean("soldier");
System.out.println("In the Main: soldier has a gun? - " + String.valueOf(soldier.getGun() != null));
System.out.println("In the Main: soldier's gun is loaded? - " + String.valueOf(soldier.getGun().getBullet() != null));
}
}
[/code]
Gun:
[code="java"]
public class Gun {
private Bullet bullet;
public Gun() {
System.out.println("Inside gun's constructor: gun is here, bullet is ready? - " + String.valueOf(this.bullet != null));
}
public Bullet getBullet() {
return this.bullet;
}
public void setBullet(Bullet arg_bullet) {
this.bullet = arg_bullet;
}
}
[/code]
Bullet:
[code="java"]
public class Bullet {
public Bullet() {
System.out.println("Inside bullet's constructor: bullet is ready");
}
}
[/code]
XML:
[code="xml"]
<bean id="gun" class="Gun" depends-on="bullet">
<property name="gunType" value="AK-47" />
<property name="bullet" ref="bullet" />
</bean>
<bean id="bullet" class="Bullet" />
[/code]
输出:
[quote]
Inside bullet's constructor: bullet is ready
Inside gun's constructor: gun is here, bullet is ready? - false
Inside soldier's constructor: soldier is here, gun is ready? - false
In the Main: soldier has a gun? - true
In the Main: soldier's gun is loaded? - true
[/quote]
通过getBean得到了soldier,可是gun和bullet均“==null”;而当调用soldier的getGun()和gun的getBullet(),才能看到gun和bullet均“!=null”了。
请问:
1、如果main里不调getter,spring是否只初始化了各个实例,却不完成属性注入?
2、有没有什么办法,使getBean的来的soldier,让spring自动完成所有的注入,返回一个属性完整的soldoer?
谢谢
[b]问题补充:[/b]
嗯谢谢。
我想找到一种方法,让getBean()得到soldier已经能够有完整的属性(包括gun以及gun.bullet)而不必事先手动调用setter。我在想bean后处理器能否实现这样的功能?抑或有其他方法?