一步一步地配置Spring
Posted tangtong1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一步一步地配置Spring相关的知识,希望对你有一定的参考价值。
本文旨在从一个空工程一步一步地配置Spring,空工程见上一篇文章创建Maven父子工程。
##一、spring基本配置
###1. 添加spring依赖
父工程pom.xml添加spring依赖
<dependencyManagement>
<dependencies>
<!-- 使用spring的BOM管理依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- spring配置开始 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- spring配置结束 -->
</dependencies>
###2. web.xml添加spring配置
修改web.xml文件为如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/dispatcher.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
###3. 添加dispatcher.xml文件
在web工程的src/main/resources/META-INF目录下添加dispatcher.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加入下面这两个配置才能支持注解功能 -->
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 本工程拦截器 -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0" />
<property name="useExpiresHeader" value="true" />
<property name="useCacheControlHeader" value="true" />
<property name="useCacheControlNoStore" value="true" />
<property name="alwaysUseFullPath" value="true" />
</bean>
</mvc:interceptors>
<!-- 扫描包,如果用扫描则不用再写 <context:annotation-config /> -->
<context:component-scan base-package="com.alan.controller" />
<context:component-scan base-package="com.alan.service.impl" />
<context:component-scan base-package="com.alan.dao.impl" />
</beans>
###4. 添加controller/service/dao等类
下面直接贴出各实现类。
(1)TestDaoImpl.java
package com.alan.dao.impl;
import org.springframework.stereotype.Repository;
import com.alan.dao.TestDao;
@Repository("testDao")
public class TestDaoImpl implements TestDao {
@Override
public String test() {
return "../index.html";
}
}
(2)TestServiceImpl.java
package com.alan.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alan.dao.TestDao;
import com.alan.service.TestService;
@Service("testService")
public class TestServiceImpl implements TestService {
@Autowired
private TestDao testDao;
@Override
public String test() {
return testDao.test();
}
}
(3)TestController.java
package com.alan.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alan.service.TestService;
@RestController
@RequestMapping("/alan")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public String test(){
return testService.test();
}
}
###5. 访问
重新编译工程并启动tomcat,通过浏览器访问,如果出现以下内容则表示配置正确。
注意:若tomcat启动老是报org.springframework.web.context.ContextLoaderListener找不到,把Eclipse关了,并把工作空间中Server/.metadata/RemoteTempFiles等几个目录删除,重新打开Eclipse并配置Preferences且重新导入工程再试。
(防采集:本文唯一网址在CSDN上,博主会不定期更新加载其它配置,其它均为未经博主同意转载的,原文为http://blog.csdn.net/tangtong1/article/details/51442757)
##二、配置Json支持
###6. 添加Json依赖
修改父工程的pom.xml,添加以下内容:
<!-- json配置开始 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!-- json配置结束 -->
###7. 配置@ResponseBody返回Json
在web工程的dispatcher.xml文件中添加如下配置:
<!-- 加入以下配置支持@ResponseBody返回Json格式 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
<!-- 为null字段时是否显示 -->
<!-- <property name="features"> <list> <value>WriteMapNullValue</value>
<value>QuoteFieldNames</value> <value>WriteNullStringAsEmpty</value> </list>
</property> -->
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
###8. 再次访问
重启tomcat,通过浏览器再次访问,如果返回以下内容表示配置@ResponseBody正确。
注:如果Controller类上注解为@RestController则相当于方法上注解了@ResponseBody。
###9. 添加返回Model方法
新建Model,并添加对应的dao/service/controller方法返回此Model。
(1)TestModel.java
package com.alan.model;
public class TestModel {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(2)TestDaoImpl.java
@Override
public TestModel testModel() {
TestModel testModel = new TestModel();
testModel.setId(1);
testModel.setName("tt");
return testModel;
}
(3)TestServiceImpl.java
@Override
public TestModel testModel() {
return testDao.testModel();
}
(4)TestController.java
@RequestMapping("/test-model")
public TestModel testModel(){
return testService.testModel();
}
###10. 访问
重启tomcat,通过浏览器访问,如果返回以下内容则表示json配置正确。
(防采集:本文唯一网址在CSDN上,博主会不定期更新加载其它配置,其它均为未经博主同意转载的,原文为http://blog.csdn.net/tangtong1/article/details/51442757)
##三、配置单元测试
###11. 添加单元测试依赖
修改父工程pom.xml,添加单元测试依赖。
<!-- 单元测试开始 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 单元测试结束 -->
###12. 添加测试类
新建一个测试类。
package com.alan.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alan.service.TestService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath*:META-INF/dispatcher.xml")
public class UnitTest {
@Autowired
private TestService testService;
@Test
public void test(){
String result = testService.test();
System.out.println(result);
}
}
###13. 运行测试类
Run As --> JUnit Test,运行结果如下表示配置单元测试正确。
(防采集:本文唯一网址在CSDN上,博主会不定期更新加载其它配置,其它均为未经博主同意转载的,原文为http://blog.csdn.net/tangtong1/article/details/51442757)
##四、配置日志管理
此处介绍两种日志管理工具,一个是log4j,一个是logback。
(一)log4j
###14. 添加log4j相关依赖
修改父工程的pom.xml,添加以下内容。
<!-- 日志配置开始 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<!-- 日志配置结束 -->
###15. 添加log4j.properties
在web工程的src/main/resources目录下添加log4j.properties文件。
log4j.rootCategory=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
log4j.category.org.springframework.beans.factory=DEBUG
修改log4j.rootCategory中的DEBUG为INFO/ERROR等即可输出相应级别的日志。
###16. 测试log4j
修改单元测试类为如下。
package com.alan.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alan.controller.TestController;
import com.alan.service.TestService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath*:META-INF/dispatcher.xml")
public class UnitTest {
private Logger logger = LoggerFactory.getLogger(UnitTest.class);
@Autowired
private TestService testService;
@Test
public void test(){
logger.debug("---------------------测试开始----------------------------");
String result = testService.test()以上是关于一步一步地配置Spring的主要内容,如果未能解决你的问题,请参考以下文章
从 React Native init 一步一步地 React Native Web
markdown 一步一步地在Xcode中创建一个好的项目环境