springboot最佳实践:在Spring Boot启动时添加方法运行
在开发Spring Boot应用程序时,有时我们需要在启动时运行方法或一段代码。这段代码可以是任何内容,从记录某些信息到设置数据库,cron作业等。我们不能仅将此代码放入构造函数中,因为所需的变量或服务可能尚未初始化。这可能导致空指针或其他一些异常。
为什么我们需要在Spring Boot启动时运行代码?
由于多种原因,我们需要在应用程序启动时运行方法,
- 记录重要的事情或说应用程序已启动的消息
- 处理数据库或文件,建立索引,创建缓存等。
- 启动后台进程,例如发送通知,从某些队列中获取数据等。
在Spring Boot中启动后运行方法的不同方法
每种方式都有其自身的优势。让我们详细看一下以确定应该使用哪个,
- 使用CommandLineRunner界面
- 带有ApplicationRunner界面
- Spring Boot应用程序事件
- @Postconstruct方法的注释
- InitializingBean接口
- @bean批注的Init属性
1.使用CommandLineRunner界面
CommandLineRunner是一个弹簧启动功能界面,用于在应用程序启动时运行代码。它位于软件包org.springframework.boot下。
在上下文初始化之后的启动过程中,spring boot使用提供给应用程序的命令行参数调用其run()方法。
要通知spring boot我们的commandlineRunner接口,我们可以实现它并在类上方添加@Component批注,或者使用@bean创建其bean。
实现CommandLineRunner接口的示例
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("In CommandLineRunnerImpl ");
for (String arg : args) {
System.out.println(arg);
}
}
}
创建CommandLineRunner接口Bean的示例
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner CommandLineRunnerBean() {
return (args) -> {
System.out.println("In CommandLineRunnerImpl ");
for (String arg : args) {
System.out.println(arg);
}
};
}
}
我们可以使用命令行或IDE运行应用程序。让我们举一个例子,当我们使用参数“ –status = running”运行应用程序时
mvn spring-boot:run -Dspring-boot.run.arguments="--status=running"
要么
mvn p