认识Spirng之 SpringBoot 初始化代码

一、CommandLineRunner/ApplicationRunner接口

@SpringBootApplication
@Slf4j
public class HelloSpringApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(HelloSpringApplication.class, args);
    }

    @RequestMapping("/hello")
    public String hello (){
        return "hello spring";
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("~~~~~~~~~ HelloSpringApplication 启动完成");
    }
}

只需实现CommandLineRunner接口,并重写run方法即可。打印如下:

 

 

 

ApplicationRunner 与CommandLineRunner 的区别在于参数不同

因为是接口所以可以多个类实现,如果多个类实现了,使用@order保证顺序

初始化执行顺序

如下代码所示:

 

 

 打印结果如下:

 

 

注:使用@Bean方法Order测试失效,

在application中添加两个bean代码如下:

@SpringBootApplication
@Slf4j
public class HelloSpringApplication  {

    public static void main(String[] args) {
        SpringApplication.run(HelloSpringApplication.class, args);
    }

    @RequestMapping("/hello")
    public String hello (){
        return "hello spring";
    }

    @Bean
    @Order(4)
    public CommandLineRunner runner4(){
        return new CommandLineRunner (){
            @Override
            public void run (String... args){
                System.out.println("CommandLineRunner runner4 run() order 4");
            }
        };
    }
    @Bean
    @Order(3)
    public CommandLineRunner runner3(){
        return new CommandLineRunner (){
            @Override
            public void run (String... args){
                System.out.println("CommandLineRunner runner3 run() order 3");
            }
        };
    }
}

执行后顺序如下:

 

 

在application中添加的初始化方法是按顺序而不是按order,
看注解的源码可以看到该注解可以写字类和方法中,具体不知为什么方法没有生效。有明白的朋友不妨留言

 

 

参考文章:

https://blog.csdn.net/wayne_ren/article/details/84877006

posted @ 2020-01-20 14:00  苦心明  阅读(408)  评论(0)    收藏  举报