Discuss / 手写Spring / WebMvcConfiguration 注入 ServletContext问题

WebMvcConfiguration 注入 ServletContext问题

Topic source

老师您好,请教下 

@Configurationpublic class WebMvcConfiguration {


    private static ServletContext servletContext = null;    
    public static void setServletContext(ServletContext ctx) {
        servletContext = ctx;    }

    @Bean(initMethod = "init")
    ViewResolver viewResolver(
            @Autowired ServletContext servletContext,            
            @Value("${summer.web.freemarker.template-path:/WEB-INF/templates}") String templatePath,            
            @Value("${summer.web.freemarker.template-encoding:UTF-8}") String templateEncoding
            ) {
        return new FreeMarkerViewResolver(servletContext, templatePath, templateEncoding);    }

    @Bean    
ServletContext servletContext() {
        return Objects.requireNonNull(servletContext, "ServletContext is not set.");    }

}

在本节webapp项目中是如何自动注入 ServletContext

在上一节的测试中,是主动调用 

WebMvcConfiguration.setServletContext

给 WebMvcConfiguration 类设置静态成员;而在此节webapp中,没有调用 setServletContext 方法**,IoC容器是如何持有和使用 ServletContext 实例的?麻烦老师解答下,谢谢您。**

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

ContextLoaderListener负责注入到WebMvcConfiguration,webapp直接@import(WebMvcConfiguration.class)就可以用了


  • 1

Reply