Springboot启动后怎么执行

发布时间:2023-04-17 10:44:34 作者:iii
来源:亿速云 阅读:97

这篇文章主要介绍了Springboot启动后怎么执行的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Springboot启动后怎么执行文章都会有所收获,下面我们一起来看看吧。

一、注解@PostConstruct

使用注解@PostConstruct是最常见的一种方式,存在的问题是如果执行的方法耗时过长,会导致项目在方法执行期间无法提供服务。

@Component
public class StartInit {
//
//    @Autowired   可以注入bean
//    ISysUserService userService;

    @PostConstruct
    public void init() throws InterruptedException {
        Thread.sleep(10*1000);//这里如果方法执行过长会导致项目一直无法提供服务
        System.out.println(123456);
    }
}

二、CommandLineRunner接口

实现CommandLineRunner接口 然后在run方法里面调用需要调用的方法即可,好处是方法执行时,项目已经初始化完毕,是可以正常提供服务的。

同时该方法也可以接受参数,可以根据项目启动时: java -jar demo.jar arg1 arg2 arg3 传入的参数进行一些处理。

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(Arrays.toString(args));
    }
}

三、实现ApplicationRunner接口

实现ApplicationRunner接口和实现CommandLineRunner接口基本是一样的。

唯一的不同是启动时传参的格式,CommandLineRunner对于参数格式没有任何限制,ApplicationRunner接口参数格式必须是:–key=value

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            List<String> values = args.getOptionValues(optionName);
            System.out.println(values.toString());
        }
    }
}

四、实现ApplicationListener

实现接口ApplicationListener方式和实现ApplicationRunner,CommandLineRunner接口都不影响服务,都可以正常提供服务,注意监听的事件,通常是ApplicationStartedEvent 或者ApplicationReadyEvent,其他的事件可能无法注入bean。

@Component
public class ApplicationListenerImpl implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("listener");
    }
}

五、四种方式的执行顺序

注解方式@PostConstruct 始终最先执行

如果监听的是ApplicationStartedEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之前执行。

如果监听的是ApplicationReadyEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之后执行。

CommandLineRunner和ApplicationRunner 默认是ApplicationRunner先执行,如果双方指定了@Order 则按照@Order的大小顺序执行,大的先执行。

关于“Springboot启动后怎么执行”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Springboot启动后怎么执行”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 网红框架SpringBoot2.x之花式运行项目
  2. 怎么解决springboot jar部署时文件/图片路径问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:Jetpack Compose选择器怎么使用

下一篇:useEffect返回函数执行过程是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》