springmvc獲取上下文ApplicationContext
1、可通過下面工具類獲取
package org.mvc.demo.utlis; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextUtil implements ApplicationContextAware{ private static ApplicationContext applicationContext;//spring上下文 @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext=applicationContext; } public static ApplicationContext getApplicationContext(){ return applicationContext; } public static <T> T getBean(String name) throws BeansException{ return (T)applicationContext.getBean(name); } }
主要是實現ApplicationContextAware介面
當一個類實現了這個介面(ApplicationContextAware)之後,這個類就可以方便獲得ApplicationContext中的所有bean。換句話說,就是這個類可以直接獲取spring配置檔案中,所有有引用到的bean物件。
另外要注意Spring上下文和SpringMVC上下文的區別。
Spring上下文配置
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-application.xml</param-value> </context-param> <!-- Spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
SpringMVC上下文配置
<servlet> <servlet-name>SpringMVC</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> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
注意:SpringMVC上下文和Spring上下文是分開獨立,兩者是父子關係。Spring 父------SpringMVC 子。但是SpringMVC上下文是可以取得Spring上下文。反之則不行。
在tomcat服務啟動日誌中可以看到,root WebApplicationContext就是Spring的。
再回頭來看,我們的SpringContextUtil,它應該放在Spring裡面來設定,才有效。放在SpringMVC裡面是沒法完成自動例項化的。
那麼,我們能仿SpringContextUtil建立springMVC的工具類嗎?答案是可以。
在做這個之前,我們要先理解springMVC的載入順序.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="false">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring-application.xml
</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>600000</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webPath</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</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>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
上面貼出的就是web.xml的部分配置,在這裡我們首先講解下web專案啟動的載入順序:以Tomcat舉例,啟動Tomcat之後,首先會載入web.xml檔案:
a)容器首先讀取web.xml中的<context-param>的配置內容和<listener>標籤中配置項;
b)緊接著例項化ServletContext物件,並將<context-param>配置的內容轉化為鍵值傳遞給ServletContext;
c)建立<listener>配置的監聽器的類例項,並且啟動監聽;
d)呼叫listener的contextInitialized(ServletContextEvent args)方法,ServletContext= ServletContextEvent.getServletContext();
此時你可以通過ServletContext獲取context-param配置的內容並可以加以修改,此時Tomcat還沒完全啟動完成。
e)後續載入配置的各類filter;
f)最後載入servlet;
最後的結論是:web.xml中配置項的載入順序是context-param=>listener=>filter=>servlet,配置項的順序並不會改變載入順序,但是同類型的配置項會應該載入順序,servlet中也可以通過load-on-startup來指定載入順序。
明白載入順序之後,我們就可以寫一個springMVC上下文的工具類了。
前面說過:這裡載入的是spring上下文
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring-application.xml
</param-value>
</context-param>
這裡載入的才是springMVC上下文
<servlet>
<servlet-name>dispatcher</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>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
這個時候我們看一下spring-mvc.xml這個檔案。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.fwone.controller"></context:component-scan>
<mvc:default-servlet-handler />
<!--mvc:annotation-driven會自動註冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean,
這是Spring MVC為@Controller分發請求所必需的,並且提供了資料繫結支援-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="fastJsonConfig">
<bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
<property name="serializerFeatures">
<list>
<value>QuoteFieldNames</value>
<value>WriteDateUseDateFormat</value>
<!-- 禁用fastjson迴圈引用檢測 -->
<value>DisableCircularReferenceDetect</value>
</list>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- FreeMarker檢視解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
<property name="contentType" value="text/html; charset=utf-8"/>
<property name="cache" value="true"/>
<property name="suffix" value=".html"/>
<property name="prefix" value=""/>
<property name="requestContextAttribute" value="rc" />
<property name="order" value="0"/>
</bean>
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/page/"/>
</bean>
<!-- Kaptcha驗證碼生成器 -->
<bean name="producer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<prop key="kaptcha.border">no</prop>
<prop key="kaptcha.textproducer.font.color">black</prop>
<prop key="kaptcha.textproducer.char.space">5</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
</beans>
主要看這裡
<context:component-scan base-package="com.fwone.controller"></context:component-scan>
我們知道,像Controller都是單獨掃描並例項化各個Controller,所以我們要在com.fwone.controller這個包下寫我們的springMVC上下文工具類
到了這裡,基本都理解清楚了。直接複製之前的spring上下文工具類
package com.fwone.controller;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
@Controller
public class SpringMvcContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;//springMVC上下文定義
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringMvcContext.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return SpringMvcContext.applicationContext;
}
public static<T> T getBean(String name)throws BeansException{
return (T)applicationContext.getBean(name);
}
}