在Spring Boot项目中,可以通过实现CommandLineRunner或ApplicationRunner接口来实现开机启动。这两个接口都有一个run()方法,程序启动后会自动执行该方法。

实现CommandLineRunner接口的示例代码如下:

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... strings) throws Exception {
        // 在这里实现开机启动需要执行的代码
    }
}

实现ApplicationRunner接口的示例代码如下:

@Component
public class MyApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 在这里实现开机启动需要执行的代码
    }
}

需要注意的是,实现这两个接口的类需要添加@Component注解,以让Spring Boot自动扫描并注入到程序中。

除了实现接口外,还可以在application.properties文件中添加配置,来实现开机启动。示例代码如下:

spring.application.name=my-project
spring.main.web-environment=false
spring.main.sources=com.example.MyApplication
spring.main.run-application=true

其中,spring.main.run-application=true表示程序启动时自动运行。需要注意的是,此方式不支持传参,如果需要传参,建议使用实现接口的方式。

springboot项目开机启动

原文地址: https://www.cveoy.top/t/topic/bVMO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录