Reputation: 13213
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?
Upvotes: 24
Views: 45158
Reputation: 2752
Another approach, just add an initializer block in YourApplication.class
.
Seeing a bug in SpringBoot 2.5.3. If I add a spring.main.lazy-initialization=true
, this initializer block will be ignored. So add a LazyInitializationExcludeFilter as a workaround.
BTW, I don't make it a static initializer block for it's friendly with @SpringBootTest
.
@SpringBootApplication
public class YourApplication {
{
your_init();
}
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
@Bean
public static LazyInitializationExcludeFilter integrationExcludeFilter() {
return (beanName, beanDefinition, beanType) -> beanType.equals(YourApplication.class);
}
}
Upvotes: 0
Reputation: 1209
Another approach prior to Spring Boot 3.4.0 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
Upvotes: 27
Reputation: 9
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.
Upvotes: 0
Reputation: 33101
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.
Upvotes: 58