此时情绪此时天,无事小神仙
好好生活,平平淡淡每一天

编辑

@Component @PostConstruct @Order ApplicationRunner CommandLineRunner

@Component中static优先于@PostConstruct优先于ApplicationRunner优先于CommandLineRunner
  1. @Component 优先执行
    • @Order可执行执行顺序:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。
      @Order(value=1)
      @Order(value=2)
      @Order(value=3)
    • static 优先执行
    • @PostConstruct 在static完成后执行
  2. @Component implements ApplicationRunner 容器启动完成后 @Component完成后 执行
  3. @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");
    }
	
}
posted @ 2021-06-29 11:58  踏步  阅读(397)  评论(0编辑  收藏  举报