SpringMVC 使用 ContextLoader获取 CommonsMultipartResolver

问题

无法在 WebApplicationContext 获取 bean

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MultipartResolver resolver = context.getBean(MultipartResolver.class);
// resolver == null

目录结构

SpringMVC 使用 ContextLoader获取 CommonsMultipartResolver_第1张图片

spring-mvc.xml

CommonsMultipartResolver 所在配置文件


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="104857600"/>
    <property name="maxInMemorySize" value="4096"/>
    <property name="defaultEncoding" value="UTF-8"/>
bean>

web.xml

<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

<servlet>
    <servlet-name>spring-mvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
servlet>
<servlet-mapping>
    <servlet-name>spring-mvcservlet-name>
    <url-pattern>/url-pattern>
servlet-mapping>

答案

web.xml

<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>
        classpath:applicationContext.xml
        
        classpath:spring-mvc.xml
    param-value>
context-param>

修改 web.xml 对应位置即可获取

原因

web.xml


<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
context-param>

对应

ContextLoaderListener.java

// ContextLoaderListener.java
// 会根据 contextConfigLocation 声明的配置路径加载资源文件
// Create a new ContextLoaderListener that will create a web application context 
// based on the "contextClass" and "contextConfigLocation" servlet context-params. 
// See ContextLoader superclass documentation for details on default values for each.
public ContextLoaderListener() {}

ContextLoader.java

public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";

static {
    // Load default strategy implementations from properties file.
    // This is currently strictly internal and not meant to be customized
    // by application developers.
    try {
        ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
        defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
    }
    catch (IOException ex) {
        throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
    }
}

你可能感兴趣的:(Frame)