@Component中static优先于@PostConstruct优先于ApplicationRunner优先于CommandLineRunner
- @Component 优先执行
- @Order可执行执行顺序:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。
@Order(value=1)
@Order(value=2)
@Order(value=3)
- static 优先执行
- @PostConstruct 在static完成后执行
- @Component implements ApplicationRunner 容器启动完成后 @Component完成后 执行
- @Component implements CommandLineRunner 容器启动完成 @Component完成后 ApplicationRunner 完成后 最后执行
代码示例
@Component @Order(value = 1) @PostConstruct
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@Order(value = 1)
public class Component1 {
static {
System.out.println("\n\nHello @Component Order1 static\n");
}
@PostConstruct
public void start() {
System.out.println("\n\nHello @Component Order1 @PostConstruct\n");
}
}
@Component @Order(value = 2) @PostConstruct
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@Order(value = 2)
public class Component2 {
static {
System.out.println("\n\nHello @Component Order2 static\n");
}
@PostConstruct
public void start() {
System.out.println("\n\nHello @Component Order2 @PostConstruct\n");
}
}
@Component implements ApplicationRunner
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ComponentApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args){
System.out.println("\n\nHello @Component implements ApplicationRunner\n");
}
}
@Component implements CommandLineRunner
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class ComponentCommandLineRunner implements CommandLineRunner{
@Override
public void run(String... strings){
System.out.println("\n\nHello @Component implements CommandLineRunner\n");
}
}