这篇文章重在说明在Spring Boot应用程序中有条件地运行CommandLineRunner Bean的不同方法。
[v_blue]注:本文基于Spring Boot 3.1.2版本进行测试。[/v_blue]
1.使用@ConditionalOnProperty
@ConditionalOnProperty注解仅在特定属性存在或具有特定值时创建bean。

程序员导航
优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站
在本例中,CommandLineRunner只有在application.properties或application.yml文件中将db.init.enabled属性设置为true时才会执行。
@Component
@ConditionalOnProperty(
name = "db.init.enabled",
havingValue = "true",
matchIfMissing = false
)
public class DatabaseInitializer implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("This runs when 'db.init.enabled' property is true.");
}
}
application.properties:
db.init.enabled=true
2.使用Environment
我们可以使用Environment bean和if语句在程序中检查条件。
在这个例子中,CommandLineRunner只有在db.init.enabled属性设置为true时才会执行。

AI 工具导航
优网导航旗下AI工具导航,精选全球千款优质 AI 工具集
@Component
public class DatabaseInitializer implements CommandLineRunner {
@Autowired
private Environment env;
@Override
public void run(String... args) {
if ("true".equals(env.getProperty("db.init.enabled"))) {
System.out.println("This runs when 'db.init.enabled' property is true.");
}
}
}
3.使用Spring Profiles
@Profile注解仅在特定Spring配置文件处于活动状态时创建bean。
在本例中,CommandLineRunner只有在Spring的dev配置文件处于活动状态时才会执行。
@Component
@Profile("dev")
public class DatabaseInitializer implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("This runs when profile is to dev.");
}
}
application.properties:
spring.profiles.active=dev
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
java -jar运行:
java -jar -Dspring.profiles.active=dev target/spring-boot-commandlinerunner-1.0.jar
4.检查其他Bean的存在性
@ConditionalOnBean和@ConditionalOnMissingBean注解仅在特定bean存在或缺失时创建bean。

免费在线工具导航
优网导航旗下整合全网优质免费、免注册的在线工具导航大全
4.1 使用@ConditionalOnBean
@ConditionalOnBean注解仅在特定bean存在于应用程序上下文中时创建bean。
在本例中,CommandLineRunner只有在BookController bean存在于应用程序上下文中时才会执行。
@Component
@ConditionalOnBean(BookController.class)
public class DatabaseInitializer implements CommandLineRunner {
@Override
public void run(String... args) {
//...
}
}
4.2 使用@ConditionalOnMissingBean
@ConditionalOnMissingBean注解仅在特定bean不存在于应用程序上下文中时创建bean。
在本例中,CommandLineRunner只有在BookController bean不存在于应用程序上下文中时才会执行。
@Component
@ConditionalOnMissingBean(BookController.class)
public class DatabaseInitializer implements CommandLineRunner {
@Override
public void run(String... args) {
//...
}
}
以上就是如何在SpringBoot中有条件地运行CommandLineRunner Bean的实现方法。



