How to set context-param in spring-boot

Since Spring Boot 2.0.0 they updated the way to add context param:

server.servlet.context-parameters.yourProperty.

You can see more updates on this link


You can set parameters using the server.servlet.context-parameters application property. For example:

server.servlet.context-parameters.p-name=p-value

In Spring Boot 1.x, which is no longer supported, this property was named server.context-parameters:

servlet.context-parameters=p-name=p-value

Alternatively, you can configure parameters programmatically by declaring a ServletContextInitializer bean:

@Bean
public ServletContextInitializer initializer() {
    return new ServletContextInitializer() {

        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setInitParameter("p-name", "-value");
        }
    };
}

You can actually achieve this using Java config. If you have filter that requires some parameters, just put them in your application.yml (or .properties), inject them using @Value in your config class and register them in FilterRegistrationBean.

For example:

@Value("${myFilterParam}")
private String myFilterParam;

@Bean(name="myFilter")
public FilterRegistrationBean myFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
    filterRegistrationBean.setInitParameters(Collections.singletonMap("p-name", "p-value"));
    return filterRegistrationBean;
}

Also JavaDoc for FilterRegistrationBean:

http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/embedded/FilterRegistrationBean.html

Update

You can register parameters for servlet context in SpringBootServletInitializer#onStartup() method. Your Application class can extend the SpringBootServletInitializer and you can override the onStartup method and set the parameters there. Example:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter("p-name", "p-value");
        super.onStartup(servletContext);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

}

Other alternative is to define ServletContextInitializer bean as suggested by Andy Wilkinson.


Also you can define InitParameterConfiguringServletContextInitializer in your configuration. Example:

@Bean
public InitParameterConfiguringServletContextInitializer initParamsInitializer() {
    Map<String, String> contextParams = new HashMap<>();
    contextParams.put("p-name", "-value");
    return new InitParameterConfiguringServletContextInitializer(contextParams);
}