Search code examples
springspring-boottomcatcomponentswar

How prevent Spring boot war file load component twice in separated context?


I have a spring boot application, packaged as a war file and deployed on tomcat server. I noticed that some component load twice in startaup:

  1. when application is started
  2. when ServletInitializer is started.

It caused me some problem because one of my components is EnableAsync and should do some scheduled task frequently. when it load twice in tow separated context each task is done twice and make duplicated rows in database.

Is there a way that force some component just load in single context in Spring boot? it means prevent bean to be initialized in ServletInitializer for example.

That's my SpringBootServletInitializer code:

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class TestApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TestApplication.class);
    }
}

Solution

  • Thanks to M. Deinum I found out there is an extra SpringBootServletInitializer in my code! I deleted it and Every thing is Ok now!