构造方法和set方法的执行顺序
- 配置文件配置如下:
<bean id="computer" class="domain.Computer"></bean>
<bean id="room" class="domain.Room">
<property name="name" value="001"></property>
<constructor-arg name="name" value="guanyu"></constructor-arg>
<constructor-arg name="computer" ref="computer"></constructor-arg>
</bean>
2.实体类:
public class Room {
private String name;
private Computer computer; //类与类关系 has a
public Room(String name, Computer computer) {
this.name = name;
this.computer = computer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Computer getComputer() {
return computer;
}
public void setComputer(Computer computer) {
this.computer = computer;
}
@Override
public String toString() {
return "Room{" +
"name='" + name + '\'' +
", computer=" + computer +
'}';
}
}
3.测试代码
Room room = (Room) factory1.getBean("room");
System.out.println(room);
4.运行结果,展示的是set方法中的值
Room{name='001', computer=Computer{brand='null', name='null', price=null}}
5.原理:因为构造方法先执行,构造方法将值赋值为guanyu后,set方法又再次给name属性赋值一次,将guanyu改为001
命名空间
- 本质上就是配置文件的一种简写
- property p:
- constructor-arg c:
举例:原来写法
<bean id="room" class="domain.Room">
<property name="name" value="001"></property>
</bean>
简写
<bean p:name="001"></bean>
1.配置文件中的头部配置文件需要配置
xmlns:c="http://www.springframework.org/schema/c"
原来写法
<bean id="room" class="domain.Room">
<constructor-arg name="name" value="guanyu"></constructor-arg>
<constructor-arg name="computer" ref="computer"></constructor-arg>
</bean>
简写
<bean id="room" class="domain.Room" c:name="guanyu" c:computer-ref="computer">
</bean>
3.测试代码
Room room = (Room) factory1.getBean("room");
System.out.println(room);
4.运行结果,展示的是set方法中的值
Room{name='guanyu', computer=Computer{brand='null', name='null', price=null}}