以前面试有做到一个题,类、构造方法、静态块的执行顺序,这几天突然想到如果在SpringBoot下的执行顺序呢?为什么不用Spring,在这个小demo中SpringBoot无需额外的配置直接可以写我想要的代码,所以这个结果对于Spring来说是一样的。Spring Boot基本上是Spring框架的扩展,它消除了设置Spring应用程序所需的XML配置,为更快,更高效的开发生态系统铺平了道路。废话不多说,代码走起!
创建一个SpringBoot项目,目录如下
config类:主要用于某类没有注解为组件,Spring无法管理。
@Configuration
public class BeanConfig {
static {
System.out.println("BeanConfig~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~静态块");
}
@Bean
public TestParent testParent(){
return new TestParent();
}
}
entity类:
//实体子
@Component
public class TestChild extends TestParent{
static{
System.out.println("TestChild类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~静态代码块");
}
{
System.out.println("TestChild类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~构造块");
}
private EntityD d = new EntityD("TestChild");
public TestChild() {
System.out.println("testChild类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~构造方法");
}
public TestChild(String str) {
System.out.println("testChild类~~~~~~~~~~~~~~~~~~~"+str+"~~~~~~~~~~~~~~~~~~~~~~~~~~~构造方法");
}
}
//实体父
public class TestParent {
static{
System.out.println("TestParent类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~静态代码块");
}
private EntityD d = new EntityD("TestParent");
public TestParent() {
System.out.println("testParent类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~构造方法");
}
}
//实体C
@Component
public class TestC {
static{
System.out.println("testC类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~静态代码块1111111");
}
private static EntityD d = new EntityD("TestC");
static{
System.out.println("testC类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~静态代码块222222");
}
public TestC() {
System.out.println("testC类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~构造方法");
}
}
//实体类D
public class EntityD {
public EntityD(String str){
System.out.println(str+"类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~EntityD成员变量");
}
}
Test测试类:
@SpringBootTest
public class DemoApplicationTests {
static {
System.out.println("DemoApplicationTests~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~静态块");
}
@Autowired
private TestC testc;
@Test
public void say(){
System.out.println("执行测试方法");
}
}
结构好了,让我们启动DemoApplicationTests中的say方法看看,输出结果吧
得到的结论:因为由Spring管理对象的生命周期,所以会扫描Component、@Configuration注解的类
1.静态代码块和静态变量的执行顺序只跟代码中出现的顺序有关,且只执行一次。(TestC的静态代码块之间)
2. 先执行父类的静态代码块和静态变量初始化,再执行子类的静态代码块和静态变量初始化。(TestB静态块先打印是因为TestA继承TestB,当Spring加载TestA时,会先去加载TestB)
3. 构造块先构造函数前执行,执行父类的实例变量初始化再执行父类的构造函数 ,然后执行子类的实例变量初始化最后执行子类的构造函数。 (实体类构造前有隐式的super(),调用父类的构造方法)