1、添加spring應用配置
在一個web工程使用spring配置的時候,首先須要進行以下四個配置。
一、在web.xml文件中添加 Spring配置文件:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/spring-mvc.xml</param-value> </context-param>
其中<param-name>的值 contextConfigLocation 爲固定值。
二、在web.xml文件中配置 Spring監聽:
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
三、開始初始化web.xml中配置的Servlet,這個servlet能夠配置多個,以最多見的DispatcherServlet爲例,這個servlet其實是一個標準的前端控制器,用以轉發、匹配、處理每一個servlet請求。
<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/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
四、在spring.xml中配置自動掃描
<context:component-scan base-package="cn.com.myspring"></context:component-scan>
還能夠加上 <context:exclude-filter> 排除不須要掃描的註解,如:
<context:component-scan base-package="com.linkage.edumanage">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
添加掃描某些註解
<context:component-scan base-package="com.brolanda.cloud" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
2、LOG4J加載配置
除了上述加載啓動Spring須要配置以上配置文件後,若是須要自建的工程使用LOG4J日誌系統,則須要在web.xml中添加以下配置
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/spring/log4j.properties</param-value>
</context-param>
<listener>
<description>Log4j配置加載器</description>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
3、Sping註解
一、@RestController 和@controller
知識點:@RestController註解至關於@ResponseBody + @Controller合在一塊兒的做用
1) 若是隻是使用@RestController註解Controller,則Controller中的方法沒法返回jsp頁面,或者html,配置的視圖解InternalResourceViewResolver不起做用,返回的內容就是Return 裏的內容。
2) 若是須要返回到指定頁面,則須要用 @Controller配合視圖解析器InternalResourceViewResolver才行。若是須要返回JSON,XML或自定義mediaType內容到頁面,則須要在對應的方法上加上@ResponseBody註解。
例如:
1.使用@Controller 註解,在對應的方法上,視圖解析器能夠解析return 的jsp,html頁面,而且跳轉到相應頁面
若返回json等內容到頁面,則須要加@ResponseBody註解
目前在寫API的時候大部分都是使用的 @RestController註解。
4、加載本地配置文件 application-*.properties
<!-- 添加本地配置文件,能夠用註解@Value獲取值-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application-*.properties</value>
<!--<value>file:${user.dir}/application-*.properties</value>-->
</list>
</property>
</bean>