非Web非批处理Spring Boot应用程序的应用程序逻辑应该放在哪里?

时间:2018-11-05 19:25:40

标签: spring-boot

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

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

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

2 个答案:

答案 0 :(得分:2)

如果使用CommandLineRunner注释对@Profile bean进行注释,则可以告诉Spring仅在具有(或不具有)某些配置文件的情况下运行该bean,例如:

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

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

答案 1 :(得分:2)

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

@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