Where should I place the application logic of non-web, non-batch Spring Boot app?

Viewed 126

I'm trying to start my non-web/non-batch Spring boot application properly.

However, if I place the main tasks in a CommandLineRunner it also gets triggered while running the tests. Running the tasks as batch job will work, but my task doesn't follow batch job semantics.

Is extending SpringApplication class and putting the logic in run() method after super() call the standard way?

2 Answers

If you annotate your CommandLineRunner bean with the @Profile annotation, you can tell Spring to only create the bean when running with (or without) certain profiles, for example:

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

As long as you don't use those profile when testing, it should not be invoked. You can then run the application using the -Dspring.profiles.active=autorun parameter.

You can create a separate Component class and assign a profile

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

This class will only be initialized when the spring.profiles.active variable is not equal to 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

Related