首页 > 其他分享 >springboot应用中根据特定条件使用CommandLineRunner

springboot应用中根据特定条件使用CommandLineRunner

时间:2024-03-01 09:55:45浏览次数:33  
标签:CommandLineRunner 特定条件 springboot boot springframework bean org import

PS 使用 Spring Boot 3.1.2 进行测试

1.使用@ConditionalOnProperty

仅当特定属性存在或具有特定值时,注释@ConditionalOnProperty才会创建 bean

在此示例中,仅当或文件中的CommandLineRunner属性db.init.enabled设置为 true时才会执行application.propertiesapplication.yml


package com.mkyong;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@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.");

  }

}
db.init.enabled=true

2、使用环境

我们可以使用Environmentbeanif语句以编程方式检查条件。

在此示例中,CommandLineRunner仅当该属性db.init.enabled设置为true时才会执行。


package com.mkyong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@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 配置文件处于活动状态时,注释@Profile才会创建bean

在此示例中,CommandLineRunner仅当 Spring 活动配置文件为 时才会执行dev


package com.mkyong;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("dev")
public class DatabaseInitializer implements CommandLineRunner {

  @Override
  public void run(String... args) {

      System.out.println("This runs when profile is to dev.");

  }
}

设置Spring 活动配置文件的不同方法。

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

仅当应用程序上下文中存在或缺少特定bean时,@ConditionalOnBean@ConditionalOnMissingBean注释才会创建bean

4.1 使用@ConditionalOnBean

@ConditionalOnBean如果特定bean存在于应用程序上下文中,则注释将创建该bean

在此示例中,仅当bean存在于应用程序上下文中CommandLineRunner时才会执行BookController


package com.mkyong;

import com.mkyong.book.BookController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnBean(BookController.class)
public class DatabaseInitializer implements CommandLineRunner {

  @Override
  public void run(String... args) {

    //...

  }
}

4.2 使用@ConditionalOnMissingBean

@ConditionalOnMissingBean如果应用程序上下文中不存在特定的bean,则注释将创建该bean

在此示例中,仅当该bean 不存在于应用程序上下文中CommandLineRunner时才会执行BookController


package com.mkyong;

import com.mkyong.book.BookController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnMissingBean(BookController.class)
public class DatabaseInitializer implements CommandLineRunner {

  @Override
  public void run(String... args) {

    //...

  }
}

标签:CommandLineRunner,特定条件,springboot,boot,springframework,bean,org,import
From: https://www.cnblogs.com/pengpengboshi/p/18046305

相关文章

  • springboot将用户认证信息提取到上下文,获取用户实体
    @ServicepublicclassInfoServiceImplimplementsInfoService{@OverridepublicMap<String,String>getinfo(){//将用户认证信息从上下文中(SecurityContext)提取出来UsernamePasswordAuthenticationTokenauthenticationToken=......
  • SpringBoot
    SpringBoot特性快速创建独立Spring应用SSM:导包、写配置、启动运行直接嵌入Tomcat、JettyorUndertow(无需部署war包)【Servlet容器】linuxjavatomcatmysql:war放到tomcat的webapps下jar:java环境;java-jar重点:提供可选的starter,简化应用整合场景启动器(starter)......
  • springboot中实现一个接口
    实现一个接口,需要在service里写一个接口,写一个实现,在controller里写一个类chatgpt4.0:在Spring框架中,实现一个接口通常遵循一种分层的架构模式,这种模式涉及到至少三个主要部分:接口定义、服务层实现、以及控制器层。这个流程确保了应用程序的高内聚、低耦合特性,同时也符合Spring......
  • springboot 集成 Dataway
    1.Dataway简介Dataway是Hasor生态中的一员,它通过提供一个UI界面来帮助开发者完成接口配置、测试、冒烟和发布等一系列任务。用户可以在Dataway的界面中进行接口的配置,无需编写任何代码。Dataway底层基于DataQL服务聚合能力,通过DataQL语言实现接口的聚合和定义,从而消除了传统开发......
  • 关于druid与springboot版本问题
    datasource:druid:driver-class-name:${sky.datasource.driver-class-name}url:jdbc:mysql://${sky.datasource.host}:${sky.datasource.port}/${sky.datasource.database}?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=u......
  • centos7环境用docker-compose部署mysql5.7集群,redis7.2.4,springboot项目
    文件目录结构关于每个配置项及docker-compose的安装,大家可以自己查mysql配置文件master---my.cnf[mysqld]server_id=1gtid-mode=ONenforce-gtid-consistency=1binlog-ignore-db=mysqllog-bin=mysql-binbinlog_cache_size=......
  • springboot两种配置文件的使用(举例:端口号、虚拟路径配置)
    1、properties配置文件使用   2、yml配置文件、yaml配置文件 在项目中更常用 在项目中一般yml配置文件更为常用,因为yml层级更加明确、清晰,更为关注数据。 ......
  • 如何在SpringBoot中优雅地重试调用第三方API?
    1引言在实际的应用中,我们经常需要调用第三方API来获取数据或执行某些操作。然而,由于网络不稳定、第三方服务异常等原因,API调用可能会失败。为了提高系统的稳定性和可靠性,我们通常会考虑实现重试机制。本文将深入探讨如何在SpringBoot项目中优雅地重试调用第三方API,并结合代码......
  • SpringBoot 2x 系列之(七)web场景
    web场景1.SpringMVC自动配置概览SpringBootprovidesauto-configurationforSpringMVCthatworkswellwithmostapplications.(大多场景我们都无需自定义配置)Theauto-configurationaddsthefollowingfeaturesontopofSpring’sdefaults:InclusionofCont......
  • SpringBoot 2x 系列之(五)开发技巧
    开发技巧1.Lombok1.应用场景简化JavaBean的开发帮我们在编译时生成get、set、toString方法2.安装及使用引入依赖【SpringBoot已经做了版本仲裁】<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></depende......