基于Maven的Spring+SpringMvc+Mybatis+slf4j-log4j日志+Swagger2+MySQL5.7框架环境搭建

一.构建Maven工程

二.添加依赖

<properties>
<spring.version>4.2.6.RELEASE</spring.version>
<mybatis.version>3.2.7</mybatis.version>
<mysql.version>5.1.29</mysql.version>
</properties>

    <!-- Spring包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- mybatis驱动包 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>

<!-- mysql驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
</dependency>

<!-- dbcp数据源 -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.6</version>
</dependency>
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
</dependency>

<!-- junit测试包 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

<!-- json数据 -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.13</version>
</dependency>

<!-- log4j日志包 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.2</version>
</dependency>

<!-- jstl 标签库 -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- swagger -->
<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger2</artifactId>  
    <version>2.7.0</version>  
</dependency>  
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-annotations</artifactId>  
    <version>2.4.4</version>  
</dependency>  
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.4.4</version>  
</dependency>  
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-core</artifactId>  
    <version>2.4.4</version>  
</dependency>
</dependencies>

三.配置swagger2

@EnableWebMvc  
@EnableSwagger2  
@ComponentScan(basePackages = {"com.zc.web.controller"})  
@Configuration  
public class SwaggerApiConfig extends WebMvcConfigurationSupport{  

    @Bean  
    public Docket createRestApi() {  
    return new Docket(DocumentationType.SWAGGER_2)  
            .apiInfo(apiInfo())  
            .select()  
            .apis(RequestHandlerSelectors.basePackage("com.zc.web.controller"))  
            .paths(PathSelectors.any())  
            .build();  
    }  

    private ApiInfo apiInfo() {  
        return new ApiInfoBuilder()  
            .title("Spring 中使用Swagger2构建RESTful APIs")  
            .termsOfServiceUrl("")  
            .contact(new Contact("zc", "", "admin@qq.com")  )
            .version("1.1")  
            .build();  
    }  
} 

四.创建配置文件
1 点击项目右键->source folder->创建resources文件夹
2 点击resources右键->folder->创建config文件夹
3 新建jdbc.properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
jdbc.username=root  
jdbc.password=root

4 新建log4j.properties配置文件

log4j.rootLogger=debug, console, info, error, timer_info_log, timer_error_log

#Output to console(控制台打印)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss} %t %C.%M %L-line %m%n

#Output to file(根据时间输出日志到文件)
log4j.appender.timer_info_log=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.timer_info_log.Append=true  
log4j.appender.timer_info_log.File=${webapp.root}WEB-INF/logfiles/timer_info/timer_info
log4j.appender.timer_info_log.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
log4j.appender.timer_info_log.Threshold=INFO
log4j.appender.timer_info_log.layout=org.apache.log4j.PatternLayout  
log4j.appender.timer_info_log.layout.ConversionPattern=%d - %c [%t] %-5p %c %x %l - %m%n

log4j.appender.timer_error_log=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.timer_error_log.Append=true  
log4j.appender.timer_error_log.File=${webapp.root}WEB-INF/logfiles/timer_error/timer_error
log4j.appender.timer_error_log.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
log4j.appender.timer_error_log.Threshold=error
log4j.appender.timer_error_log.layout=org.apache.log4j.PatternLayout  
log4j.appender.timer_error_log.layout.ConversionPattern=%d - %c [%t] %-5p %c %x %l - %m%n

4 配置spring.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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<!-- jdbc配置 -->
<context:property-placeholder location="classpath:config/jdbc.properties" />

<!-- 自动将Service层注入 -->
<context:component-scan base-package="com.zc.service" />

<!-- dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    
    <property name="maxActive" value="20" />
    <property name="maxIdle" value="10" />
    <property name="maxWait" value="10000" />
    <property name="defaultAutoCommit" value="false" />     
</bean>

<!-- mybatis的配置文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations" value="classpath:mybatis/*.xml"></property>
</bean>

<!-- spring与mybatis整合配置,扫描所有dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.zc.dao"></property>
</bean>
</beans>

5 配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
       
 <!-- 扫描controller (controller层注入) -->
 <context:component-scan base-package="com.zc.web.controller" />    
 
 <!-- 启动注解支持 -->
 <mvc:default-servlet-handler/>
 <mvc:annotation-driven />
 
 <!-- 静态资源 -->
 <mvc:resources location="/WEB-INF/js/" mapping="/js/**" />
 <mvc:resources location="/WEB-INF/css/" mapping="/css/**" />
 <mvc:resources location="/WEB-INF/image/" mapping="/image/**"/>
 
 <!-- 视图解析器 -->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix" value="/WEB-INF/view/"></property>
    <property name="suffix" value=".jsp"></property>
 </bean>
 
 <!-- Enables swgger ui-->
 <mvc:default-servlet-handler/>
 <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
 <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
       
</beans>          

五.编程demo
接下来给大家写一个简单的新增用户demo(需要其余的demo可以联系我,到时候发给你们):
1 我用的mysql5.7,先在数据库新建一张表

CREATE DATABASE test;

USE test;

DROP TABLE IF EXISTS `user_t`;

CREATE TABLE `user_t` (
  `user_id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `user_name` VARCHAR(200) DEFAULT NULL COMMENT '姓名',
  `PASSWORD` VARCHAR(200) DEFAULT NULL COMMENT '密码',
   PRIMARY KEY (`user_id`),
   UNIQUE KEY `user_name` (`user_name`)
)COMMENT '测试用户表';  

2 现在要写mybatis对应的DaoMapper了:在这里要注意的就是参数对应的jdbcType类型要大写

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zc.dao.user.IUserDao">
<resultMap type="com.zc.model.user.UserVo" id="BaseResultMap">
    <result column="user_id" property="userId" jdbcType="VARCHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>

<sql id="Base_Column_List">
    user_id, user_name, password
</sql>

<insert id="addUser" parameterType="com.zc.model.user.UserVo">
    insert into user_t
    (
        user_name,
        password
    )
    values
    (
        #{user.userName, jdbcType=VARCHAR},
        #{user.password, jdbcType=VARCHAR}
    )
</insert>
</mapper>

3 接下来写Dao层接口

package com.zc.dao.user;

import java.util.List;

import org.apache.ibatis.annotations.Param;

public interface IUserDao {

/**
 * 新增用户信息
 * @param user
 * @return
 */
int addUser(@Param("user")UserVo user);

}

  1. 创建三个实体类
    1)用户对象实体

     package com.zc.model.user;
    
     import com.zc.common.BaseVo;
    
     public class UserVo extends BaseVo {
     private String userId;
    
     private String userName;
    
     private String password;
    
    
     public String getUserId() {
         return userId;
     }
    
     public void setUserId(String userId) {
         this.userId = userId;
     }
    
     public String getUserName() {
         return userName;
     }
    
     public void setUserName(String userName) {
         this.userName = userName;
     }
    
     public String getPassword() {
         return password;
     }
    
     public void setPassword(String password) {
         this.password = password;
     }
    
     }
    

2)UserAddRequestDto请求对象实体

package com.zc.facade.dto.request.user;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiParam;

@ApiModel(description = "新增用户请求实体")
public class UserAddRequestDto {

private static final long serivalVersionUID = 1L;

@ApiParam(value = "用户名", required = false)
private String userName;

@ApiParam(value = "用户密码", required = false)
private String password;


public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

3)UserResponseDto请求对象实体

package com.zc.facade.dto.response.user;

import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

import com.zc.facade.dto.info.UserDto;

public class UserResponseDto {

private static final long serialVersionUID = 1L;

private UserDto user;

public UserDto getUser() {
    return user;
}

public void setUser(UserDto user) {
    this.user = user;
}

}

5 创建一个IUserService接口

package com.zc.service;

import com.zc.facade.dto.request.user.UserAddRequestDto;
import com.zc.facade.dto.response.user.UserResponseDto;

public interface IUserService {

/**
 * 新增用户
 * @param requestDto
 * @return
 * @throws Exception
 */
UserResponseDto addUser(UserAddRequestDto requestDto);

}

6 创建UserServiceImpl实现类

package com.zc.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zc.common.DataGrid;
import com.zc.dao.user.IUserDao;
import com.zc.facade.dto.request.user.UserAddRequestDto;
import com.zc.facade.dto.response.user.UserResponseDto;
import com.zc.model.user.UserVo;
import com.zc.service.IUserService;

@Service("userService")
public class UserServiceImpl implements IUserService {

private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

@Resource
private IUserDao userDao;

@Override
public UserResponseDto addUser(UserAddRequestDto requestDto) {
    
    UserResponseDto responseDto = new UserResponseDto();
    
    UserVo user = new UserVo();
    user.setUserName(requestDto.getUserName());
    user.setPassword(requestDto.getPassword());
    
    try {
        int n = userDao.addUser(user);
        if(n==1){
            System.out.println("新增成功");
        }else{
            System.out.println("新增失败");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        logger.error("保存用户信息异常", e);
    }
    
    return responseDto;
}

}

7 创建UserController

package com.zc.web.controller.user;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.zc.facade.dto.request.user.UserAddRequestDto;
import com.zc.facade.dto.response.user.UserResponseDto;
import com.zc.service.IUserService;
import com.zc.web.common.ResponseUser;
import com.zc.web.common.RestMessage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "用户服务",description = "提供RESTful风格API的用户的增删改查服务")
@Controller
@RequestMapping("/user")
public class UserController {

private final static Logger logger = LoggerFactory.getLogger(UserController.class);

@Resource
private IUserService userService;

@ApiOperation(value = "新增", notes = "新增用户")
@RequestMapping(value = "/add/userVo", method = RequestMethod.GET)
@ResponseBody
public RestMessage<UserResponseDto> add(UserAddRequestDto requestDto) {
    
    logger.info("add method start,the parameter is :");
    logger.info("requestDto:{},{}", requestDto.getUserName(), requestDto.getPassword());
    
    UserResponseDto responseDto = new UserResponseDto();
    
    responseDto = userService.addUser(requestDto);
    
    return new RestMessage<UserResponseDto>(responseDto);
}

}

8 新增用户demo编写完毕;

9 启动tomcat,因为配置了swagger2,我们用swagger2来测试新增接口:
http://IP:port/{context-path}/swagger-ui.html
例如:http://localhost:8080/test/swagger-ui.html

swagger-1.png
swagger-2.png

我的博客

我的博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容