如何将自定义ApplicationContextInitializer添加到Spring启动应用程序?

ash*_*ram 14 spring spring-boot

向Spring Web应用程序添加自定义ApplicationContextInitializer的一种方法是将其添加到web.xml文件中,如下所示.

<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>
Run Code Online (Sandbox Code Playgroud)

但是因为我使用的是spring boot,有没有什么办法可以创建web.xml来添加CustomApplicationContextInitializer?

Ste*_*oll 34

你可以注册 META-INF/spring.factories

org.springframework.context.ApplicationContextInitializer=\
com.example.YourInitializer
Run Code Online (Sandbox Code Playgroud)

您也可以SpringApplication在运行之前将它们添加到您的上面

application.addInitializers(YourInitializer.class);
application.run(args);
Run Code Online (Sandbox Code Playgroud)

或者在建筑商身上

new SpringApplicationBuilder(YourApp.class)
    .initializers(YourInitializer.class);
    .run(args);
Run Code Online (Sandbox Code Playgroud)

从初看起来的文件来看并不明显,所以我打开了#5091进行检查.

  • 或者属性文件中的`context.initializer.classes = com.example.YourInitializer`.我喜欢这种方法,因为您可以通过特定于环境的属性文件启用/禁用初始化程序 (5认同)

Jef*_*ets 11

另一种方法是context.initializer.classes=com.example.YourInitializer在properties/yml文件中使用.我喜欢这种方法,因为您可以通过特定于环境的道具文件启用/禁用初始化程序.

它只是在spring boot docs中简要提到过