22

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?

ajm
  • 12,863
  • 58
  • 163
  • 234

3 Answers3

53

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.

Stephane Nicoll
  • 31,977
  • 9
  • 97
  • 89
  • 10
    Or `context.initializer.classes=com.example.YourInitializer` in a properties file. I like this approach because then you can enable/disable initializers via environment specific properties files – Jeff Sheets Nov 17 '16 at 23:06
  • 1
    @JeffSheets it works and it's the most convenient for me, you should post it as an answer – ZZ 5 Sep 01 '17 at 08:18
  • [Spring Boot documentation reference](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-environment-or-application-context) – cdalxndr May 14 '20 at 19:38
26

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

Jeff Sheets
  • 1,181
  • 12
  • 18
0

Another option is using @ContextConfiguration annotation at class level like this:

@ContextConfiguration(initializers = [TestContainersInitializer::class])

This way is useful to add this initializer to a test class for example to start docker containers before executing tests.