小编典典

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

spring-boot

spring-boot-starter-parent用作父项并添加spring-boot-starter-web为依赖项。

通过添加@SpringBootApplication注释,它可以工作。

但是DispatcherServlet需要初始化

     Initializing servlet 'dispatcherServlet'
     FrameworkServlet 'dispatcherServlet': initialization started
     Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver@745f40ac]
     Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@219fc57d]
     Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver@7b4bd6bd]
     Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@71ccfa36]
     Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@43f3e6a9]
     Published WebApplicationContext of servlet 'dispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet]
     FrameworkServlet 'dispatcherServlet': initialization completed in 37 ms

我希望我可以将它的loadonstartupup设置为1,并且不想使用这个令人讨厌的方法BeanNameUrlHandlerMapping,它拒绝了所有操作,并且我将不使用它。

o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'contextAttributes': no URL paths identified

我阅读了有关的Java文档BeanNameUrlHandlerMapping

这是org.springframework.web.servlet.DispatcherServlet和org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping(在Java
5及更高版本上)一起使用的默认实现。另外,SimpleUrlHandlerMapping允许声明性地自定义处理程序映射。

就是这样,我只想更改这两件事:

  1. setLoadonStartup
  2. 不要使用BeanNameUrlHandlerMapping

除此之外,spring boot为我配置的其他东西也很棒,我想保留它。

感谢您提供任何帮助。


阅读 3943

收藏
2020-05-30

共1个答案

小编典典

我也遇到了同样的问题loadOnStartup。我通过使用自定义解决它BeanFactoryPostProcessor修改BeanDefinitionServletRegistrationBean那个spring启动创建用于注册DispatcherServlet

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

@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);
        }
    };
}
2020-05-30