Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 951
ashishjmeshram Avatar asked Feb 05 '16 06:02

ashishjmeshram


People also ask

What is the use of ApplicationContextInitializer?

ApplicationContextInitializer processors are encouraged to detect whether Spring's Ordered interface has been implemented or if the @Order annotation is present and to sort instances accordingly if so prior to invocation.

What is ConfigurableApplicationContext spring boot?

public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable. SPI interface to be implemented by most if not all application contexts. Provides facilities to configure an application context in addition to the application context client methods in the ApplicationContext interface.

What is SpringApplicationBuilder?

public class SpringApplicationBuilder extends Object. Builder for SpringApplication and ApplicationContext instances with convenient fluent API and context hierarchy support.


2 Answers

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.

like image 50
Stephane Nicoll Avatar answered Sep 19 '22 09:09

Stephane Nicoll


Another approach is to use context.initializer.classes=com.example.YourInitializer in a properties/yml file. I like this approach because then you can enable/disable initializers via environment specific props files.

It is mentioned only briefly in the spring boot docs

like image 37
Jeff Sheets Avatar answered Sep 19 '22 09:09

Jeff Sheets