Spring boot中如何使用CommandLineRunner接口实现初始化呢?
下文笔者讲述SpringBoot中使用commandlinerunner接口实现初始化的方法及示例分享,如下所示
CommandLineRunner可实现
应用程序初始化后
运行一段代码逻辑
整个生命周期只会运行一次
================================================
下文笔者讲述三种方式使用CommandLineRunner
同@Component注解一起使用
@Component
public class ApplicationStartupRunner implements CommandLineRunner {
protected final Log logger = LogFactory.getLog(getClass());
@Override
public void run(String... args) throws Exception {
logger.info("ApplicationStartupRunner run method Started !!");
}
}
同@SpringBootApplication注解一起使用
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer implements CommandLineRunner {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootWebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
logger.info("Application Started !!");
}
}
实现CommandLineRunner接口的Bean
public class ApplicationStartupRunner implements CommandLineRunner {
protected final Log logger = LogFactory.getLog(getClass());
@Override
public void run(String... args) throws Exception {
logger.info("Application Started !!");
}
}
注册ApplicationStartupRunner bean
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootWebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
@Bean
public ApplicationStartupRunner schedulerRunner() {
return new ApplicationStartupRunner();
}
}
设置多个CommanderLineRunner的运行顺序
@Order(value=3)
@Component
class ApplicationStartupRunnerOne implements CommandLineRunner {
protected final Log logger = LogFactory.getLog(getClass());
@Override
public void run(String... args) throws Exception {
logger.info("ApplicationStartupRunnerOne run method Started !!");
}
}
@Order(value=2)
@Component
class ApplicationStartupRunnerTwo implements CommandLineRunner {
protected final Log logger = LogFactory.getLog(getClass());
@Override
public void run(String... args) throws Exception {
logger.info("ApplicationStartupRunnerTwo run method Started !!");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


