springspring-boot

How to add custom ApplicationContextInitializer to a spring boot application?


One way to add custom ApplicationContextInitializer to spring web application is to add it in the web.xml file as shown below.

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>somepackage.CustomApplicationContextInitializer</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

But since I am using spring boot, is there any way I don't have to create web.xml just to add CustomApplicationContextInitializer?


Solution

  • You can register them in META-INF/spring.factories

    org.springframework.context.ApplicationContextInitializer=\
    com.example.YourInitializer
    

    You can also add them on your SpringApplication before running it

    application.addInitializers(YourInitializer.class);
    application.run(args);
    

    Or on the builder

    new SpringApplicationBuilder(YourApp.class)
        .initializers(YourInitializer.class);
        .run(args);
    

    It wasn't obvious from the doc at first glance so I opened #5091 to check.