Spring初始化顺序,疑难解惑

前段时间一直被问到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的初始化正常情况会根据配置文件从上往下依次读取初始化各个类或组件,不过当遇到某个类依赖其他类的时候,如果该类未被初始化,将会跳过从上往下依次顺序先初始化该类。再者属性的初始化,是在类被初始化之后被注入到类中。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值