Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Use Application Listener

After starting my spring boot application I want to start an customer process like creating required folders, files, etc. For that I'm using ApplicationListener<ApplicationReadyEvent>. This works like expected. But I'm building my spring application context with SpringApplicationBuilder. Every child notifies that the application is started correctly. So my customer post-process startes even more than one time.

@SpringBootApplication
@EnableConfigurationProperties(value = {StorageProperties.class})
@EnableAsync
public class Application {

  public static void main(String[] args) {

    SpringApplicationBuilder parentBuilder
            = new SpringApplicationBuilder(Application.class);

    parentBuilder.child(Config1.class)
            .properties("server.port:1443")
            ...
            .run(args);
    parentBuilder.child(Config2.class)
            .properties("server.port:2443")
            ...
            .run(args);
  }
}

My first idea was, that I can create manuelly a new Bean with @Bean in Config1 for my Event-Listener. But I was not able to overhand the configuration file StorageProperties.class, which is necessary for this class.

Because the Listener has an constructor based dependency injection:

private final Path mPathTo;
public AfterStart(StorageProperties prop) {
    this.mPathTo = Paths.get(prob.getPath());
}

How can I be able to start the listener just once per start?

like image 357
LeckerMaedschen Avatar asked Sep 15 '25 12:09

LeckerMaedschen


1 Answers

For everyone who is interested in this question. This solution worked for me:

public void onApplicationEvent(ApplicationReadyEvent e) {
    if (e.getApplicationContext().getParent == null) {
        System.out.println("******************************");
        System.out.println("Post-process begins.");
        System.out.println("******************************");      
    }
}
like image 135
LeckerMaedschen Avatar answered Sep 18 '25 10:09

LeckerMaedschen