文章目录 1.使用@ConditionalOnProperty 2.使用Environment 3.使用Spring Profiles 4.检查其他Bean的存在性 4.1 使用@ConditionalOnBean 4.2 使用@ConditionalOnMissin……
文
章
目
录
- 1.使用@ConditionalOnProperty
- 2.使用Environment
- 3.使用Spring Profiles
- 4.检查其他Bean的存在性
- 4.1 使用@ConditionalOnBean
- 4.2 使用@ConditionalOnMissingBean
这篇文章重在说明在Spring Boot应用程序中有条件地运行CommandLineRunner Bean的不同方法。
注:本文基于Spring Boot 3.1.2版本进行测试。
1.使用@ConditionalOnProperty
@ConditionalOnProperty注解仅在特定属性存在或具有特定值时创建bean。
在本例中,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时才会执行。
@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
Spring Boot Maven 插件.
./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的实现方法。
还没有评论呢,快来抢沙发~