问题
无法在 WebApplicationContext
获取 bean
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MultipartResolver resolver = context.getBean(MultipartResolver.class);
// resolver == null
目录结构
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>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
答案
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
<!-- 重点, ContextLoaderListener 需要加载 CommonsMultipartResolver 所在的配置文件 -->
classpath:spring-mvc.xml
</param-value>
</context-param>
修改 web.xml
对应位置即可获取
原因
web.xml
<!-- web.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-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());
}
}