且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过Spring Boot在启动时配置'dispatcherServlet'负载?

更新时间:2023-09-06 15:53:04

我遇到了与loadOnStartup相同的问题.我通过使用自定义BeanFactoryPostProcessor修改了Spring Boot为注册DispatcherServlet而创建的ServletRegistrationBeanServletRegistrationBean来解决了这个问题.

I encountered the same problem with loadOnStartup. I solved it by using a custom BeanFactoryPostProcessor to modify the BeanDefinition of the ServletRegistrationBean that Spring Boot creates for registering the DispatcherServlet.

@Configuration类中使用以下代码时,将在Spring Boot应用程序中为DispatcherServlet设置loadOnStartup:

The following code will set loadOnStartup for the DispatcherServlet in a Spring Boot app, when used within an @Configuration class:

@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
    return new BeanFactoryPostProcessor() {

        @Override
        public void postProcessBeanFactory(
                ConfigurableListableBeanFactory beanFactory) throws BeansException {
            BeanDefinition bean = beanFactory.getBeanDefinition(
                    DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);

            bean.getPropertyValues().add("loadOnStartup", 1);
        }
    };
}