springboot
1、main.run方法进入
2、refreshContext
3、refresh
4、finishBeanFactoryInitialization(完成beanFactory的初始化)
5、preInstantiateSingletons(初始化单例)
6、getBean(获取Bean)
7、doGetBean
8、createBean
9、doCreateBean(此方法内部会createBean,创建bean即构造方法执行)
10、populateBean(进行autowired自动注入)
11、applyPropertyValues(进行属性注入)
PS:new对象,不能导致对象依赖的注入属性自动赋值,只有对对象进行注入,对象依赖的注入属性才能赋值;
且注入的属性不能在构造函数中操作,因为bean没有创建完成,属性也没有注入,此时是为null的
问题:spring默认是单例模式,还有必要创建单例类吗?
自己理解:有必要,如果不使用autowired进行自动注入,使用new操作还是可以生成多个对象,
spring的单例是针对自动注入
例子:
@Component
public class CxfClient{
@Value("${address }")
private String address;
private CxfClient(){
System.out.println(address ); //此时为null.bean没有加载完成,属性也没有加载
}
public void createClient(){
System.out.println(address );//此时为配置文件中的值
}
private static class SingletonHolder {
private static final CxfClient INSTANCE = new CxfClient();
}
public static final CxfClient getInstance() {
return SingletonHolder.INSTANCE;
}
}
public class Test{
@Autowired
private CxfClient cxfClient;
public void testClient(){
CxfClient.getInstance().createClient();//打印为null.无法注入
cxfClient.createClient();//打印为配置文件中的值
}
}