【问题标题】:Where should I place the application logic of non-web, non-batch Spring Boot app?非 web、非批处理 Spring Boot 应用的应用逻辑应该放在哪里?
【发布时间】:2019-04-09 04:41:51
【问题描述】:

我正在尝试正确启动我的非 Web/非批处理 Spring Boot 应用程序。

但是,如果我将主要任务放在 CommandLineRunner 中,它也会在运行测试时被触发。将任务作为批处理作业运行将起作用,但我的任务不遵循批处理作业语义。

在super()调用标准方式之后,是否扩展SpringApplication类并将逻辑放入run()方法中?

【问题讨论】:

  • 没有。 “标准”方式是将您的业务逻辑放在 Service 类中并从运行器调用它。
  • 您可以确保只为某些配置文件创建CommandLineRunner。因此,如果您这样做,并确保在执行测试时不使用这些配置文件,我认为没有任何问题?
  • 调用我的服务的命令行运行器也会在我运行单元测试时被调用。
  • 谢谢@g00glen00b。这对我有用。

标签: spring-boot


【解决方案1】:

如果您使用 @Profile 注释来注释您的 CommandLineRunner bean,您可以告诉 Spring 仅在使用(或不使用)某些配置文件运行时创建 bean,例如:

@Component
@Profile("autorun")
public class JobRunner implements CommandLineRunner {
    // ...
}

只要您在测试时不使用这些配置文件,就不应调用它。然后您可以使用-Dspring.profiles.active=autorun 参数运行应用程序。

【讨论】:

    【解决方案2】:

    您可以创建一个单独的组件类并分配一个配置文件

    @Component
    @Profile("!test")
    public class RunApplication implements CommandLineRunner {
        @Override
        public void run(String... args) throws IOException {
            //Your code here 
        }
    }
    

    只有当spring.profiles.active变量不等于test时才会初始化这个类

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

    https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/CommandLineRunner.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2015-02-13
      • 2017-08-11
      • 2016-12-18
      • 2014-10-26
      • 2012-07-16
      相关资源
      最近更新 更多