Spring Bean 的生命周期大致分为:Bean定义,Bean初始化,Bean的生存期,Bean的销毁四个部分
a. 资源定位:
Spring 通过我们的配置 如@ComponentScan 定义扫描路径去找带有@Component的类,
这个过程就是一个资源定位的过程。
b.Bean定义:
一旦找到了资源,他就开始解析,并将信息保存起来。注意此时还没有初始化Bean,
也就没有Bean实例,它有的仅仅是Bean的定义。然后将Bean定义发送到IOC容器中。
此时依然只有定义。
c. 初始化:
经过上述步骤,spring 会继续完成Bean 实例化和依赖注入。
如果不想让spring继续初始化,可在@ComponentScan中设置lazyInit =true(默认为false)
示例如下:
package com.didispace.service.impl;
import com.didispace.service.Animal;
import com.didispace.service.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class BussinessPerson implements Person {
private Animal animal = null;
@Override
public void service() {
this.animal.use();
}
@Override
@Autowired @Qualifier("dog")
public void setAnimal(Animal animal) {
System.out.println("延迟依赖注入!!!");
this.animal = animal;
}
}
<