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>