Running Code After Spring Boot Starts

Running code after Spring Boot starts

Try:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

@SuppressWarnings("resource")
public static void main(final String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

context.getBean(Table.class).fillWithTestdata(); // <-- here
}
}

Call a method after Spring Boot app starts

Check for the @PostConstruct for e.g here https://www.baeldung.com/running-setup-logic-on-startup-in-spring

Spring Boot - Correct way to run code during / before app startup?

ApplicationRunner and CommandLineRunner are the correct interfaces to implement to execute business logic which require injected dependencies at start-up.
There is not much difference between the two.

CommandLineRunner will give you access to the raw String array of parameters passed at startup.

ApplicationRunner will give you a more structured ApplicationArguments, but that's all.

You can have multiple start-up runners, and you can even order them.


This seems hackish

No, it's not. ApplicationRunner and CommandLineRunner JavaDoc

Interface used to indicate that a bean should run when it is contained
within a SpringApplication.

How starter-web prevent spring-boot exit?

To answer the question

What's the code that spring-boot-starter-web prevent spring-boot exit

spring-boot-web creates web server beans, that use non-daemon listener threads (as you want them to be alive and running to waiting for incoming connections and handle them).

This makes your code reach end of your main method, however JVM does not exit, as it has non-daemon threads running.

If you want to keep your application alive, you'd need to do the same - the simplest way would be to e.g. create a Thread in a bean like @Slongtong has suggested.



Related Topics



Leave a reply



Submit