Spring@组件创建顺序



我试图找到上面问题的答案,但我没有。那么,Spring@组件的创建顺序是什么?例如:我们有

@Component
public class Foo extends SecondClass {
private SomeType someField;
@Autowired
public Foo(SomeType someField){
super(someField);
}
}
public class SecondClass implement ISomething {
//code and @override methods...
@PostConstruct 
public void method(ISomething i) {
//Actions with i
}
}

创作顺序是什么?在这种特殊情况下,父对象或子对象将首先创建什么?谢谢

为了简单起见,忽略将作为Spring应用程序的一部分在后台创建的bean。

由于类Foo上只有@Component,因此将创建一个Springbean。创建顺序无关紧要,因为这里只创建了一个bean,因为在任何其他类上都没有@Component。如果你想使用SecondClass,你必须自己手动实例化它

关于继承问题,Spring并没有参与其中。它将由Java自己处理。

编辑:

@PostConstruct将被忽略,因为SecondClass不是Spring bean。但由于我们使用的是super,它将被称为This,这是一个测试bean创建顺序的完整程序。

import javax.annotation.PostConstruct;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class TestProgram implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(TestProgram.class, args);
}
@Component
public static class Foo extends SecondClass {
@Override
public void method() {
System.out.println("Printing Foo class");
//new change
super.method(); 
}
}
public static class SecondClass implements Cloneable {
//Since you are calling this method via super in Foo class, you don't need 
//this annotation as it is being ignored anyway since this class is not a 
//bean.
@PostConstruct
public void method() {
System.out.println("Printing Second Class");
}
}
@Override
public void run(String... args) throws Exception {
System.out.println("Spring application is up.");
}
}

现在它将打印这两者,因为我们正在使用超级调用来调用SecondClass方法。

打印Foo类

打印二级

SecondClass中不需要@PostConstruct,因为它不是Springbean,这就是为什么在没有super调用的情况下它被忽略的原因。

通过删除/添加注释进行游戏,你会得到它。

@Order注释定义了带注释的组件或bean的排序顺序。它有一个可选的值参数,用于确定组件的顺序。所以,你可以根据它的优先级来安排你的豆子。

最新更新