Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DispatcherServeletInitializer functionality in Spring Boot

We are looking to migrate our project to Spring Boot. However it is unclear how to replicate the functionality of AbstractAnnotationConfigDispatcherServletInitializer in Spring Boot?

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
    return new Class<?>[]{AppConfig.class};
}

@Override
protected Class<?>[] getServletConfigClasses()
{
    return new Class<?>[]{WebappConfig.class};
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setAsyncSupported(true);
}

@Override
protected String[] getServletMappings()
{
    return new String[]{"/"};
}

@Override
protected Filter[] getServletFilters()
{
    DelegatingFilterProxy shiroFilter = new DelegatingFilterProxy("shiroFilter");
    shiroFilter.setTargetFilterLifecycle(true);

    CompositeFilter compositeFilter = new CompositeFilter();
    compositeFilter.setFilters(ImmutableList.of(new CorsFilter(),shiroFilter));

    return new Filter[]{compositeFilter};
}

}

like image 648
pdeva Avatar asked Aug 31 '25 20:08

pdeva


1 Answers

The AppConfig and WebappConfig parent/child relationship can be handled by SpringApplicationBuilder, although you might also consider a flat hierarchy.

Assuming that you are going the whole hog, and running an embedded servlet container you can register Filters and Servlets directly as beans.

You can also use ServletRegistrationBean and FilterRegistrationBean if you need to set things such as setAsyncSupported. The final option is to add a bean that implements org.springframework.boot.context.embedded.ServletContextInitializer then do the registration yourself.

Something like this might get you a bit further:

@Bean
public ServletRegistrationBean dispatcherServlet() {
    ServletRegistrationBean registration = new ServletRegistrationBean(
            new DispatcherServlet(), "/");
    registration.setAsyncSupported(true);
    return registration;
}

@Bean
public Filter compositeFilter() {
    CompositeFilter compositeFilter = new CompositeFilter();
    compositeFilter.setFilters(ImmutableList.of(new CorsFilter(), shiroFilter));
    return compositeFilter
}

Also, take a look at this section in the reference manual http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container

like image 195
Phil Webb Avatar answered Sep 03 '25 09:09

Phil Webb