前段时间一直被问到Spring的初始化顺序是什么,刚开始就一头雾水。简单做了和例子仅供大家参考。
首先是3个基本的Java类:
public class Customer {
private String name;
public Customer(){
System.out.println("Customer被初始化");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void showName(){
System.out.println("Customer的名称是:"+name);
}
}
public class Person {
private String name;
private Customer customer;
public Person(){
System.out.println("person被初始化"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public void showName(){
System.out.println("Person的名称是:"+name);
}
}
public class Student {
public Student(){
System.out.println("学生被初始化了");
}
}
<?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="personService" class="cn.test.service.impl.PersonServiceImpl"></bean>
<bean id="person" class="cn.test.bean.Person">
<property name="name"><value>管理员</value></property>
<property name="customer">
<ref local="customer" />
</property>
</bean>
<bean id="student" class="cn.test.bean.Student"></bean>
<bean id="customer" class="cn.test.bean.Customer">
<property name="name"><value>客户</value></property>
</bean>
</beans>
测试代码:
public class Test {
public static void main(String[] args) throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
Person p = (Person) app.getBean("person");
p.showName();
Student s = (Student) app.getBean("student");
Customer c = p.getCustomer();
c.showName();
}
}
运行结果:
person被初始化null
Customer被初始化
学生被初始化了
Person的名称是:管理员
Customer的名称是:客户
通过调换bean.xml中Customer和Person的前后位置,会发现初始化的顺序会改变,可见Spring的初始化正常情况会根据配置文件从上往下依次读取初始化各个类或组件,不过当遇到某个类依赖其他类的时候,如果该类未被初始化,将会跳过从上往下依次顺序先初始化该类。再者属性的初始化,是在类被初始化之后被注入到类中。