本次演示的代码结构如下,基于maven,整合SpringBoot、Spring、Mybaits的SSM框架。同时测试logback日志框架的使用及配置。
1.创建maven工程,修改pom.xml文件
4.0.0
yan.li
spring-boot-demo
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
1.5.8.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-cache
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
true
com.alibaba
fastjson
1.2.9
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
true
2
.创建com.liyan.model包,同时创建两个PO类
(1)User.java类
package com.liyan.model;
import java.io.Serializable;
/**
* 员工实体类
* Title: User
* @author Liyan
* @date 2018年1月11日 上午10:45:20
*/
public class User implements Serializable{
private static final long serialVersionUID = 1L;
/** 自增主键 */
private Integer id;
/** 员工工号 */
private String userId;
/** 员工姓名 */
private String userName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
(
2)ResponseResult.java类
package com.liyan.model;
/**
* 返回值实体类
* Title: ResponseResult
* @author Liyan
* @date 2018年1月11日 下午5:23:41
*/
public class ResponseResult {
private Integer code;
private String msg;
private Object data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public ResponseResult(Integer code, String msg, Object data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}
}
3.在com.liyan.mapper包下创建UserMapper.java接口
package com.liyan.mapper;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import com.liyan.model.User;
//这里可以使用@Mapper注解,但是每个mapper都加注解比较麻烦,所以统一配置@MapperScan在扫描路径在application类中
//@Mapper //声明是一个Mapper,与springbootApplication中的@MapperScan二选一写上即可
@Repository
public interface UserMapper {
@Select("SELECT id, user_id userId, user_name userName FROM user_tab WHERE user_id = #{userId}")
@ResultType(User.class)
User selectUser(String userId);
}
4.在com.liyan.service包下创建UserService.java接口
package com.liyan.service;
import com.liyan.model.User;
public interface UserService {
/**
* 根据员工工号,查询员工
* Title: selectUser
* @author Liyan
* @date 2018年1月11日 上午10:50:34
* @param userId 员工工号
* @return List
*/
public User selectUser(String userId);
}
5.在com.liyan.service.impl包下创建UserServiceImpl.java类
package com.liyan.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.liyan.mapper.UserMapper;
import com.liyan.model.User;
import com.liyan.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectUser(String userId) {
return userMapper.selectUser(userId);
}
}
6.在com.liyan.exception包下创建三个自定义异常相关的类
(1)ExceptionEnum.java类
package com.liyan.exception;
/**
* 异常枚举类
* Title: ExceptionEnum
* @author Liyan
* @date 2018年1月11日 下午3:54:48
*/
public enum ExceptionEnum {
ERROR_NOFOUND("无法找到相应的数据");
private String value;
public String getValue() {
return value;
}
ExceptionEnum(String value){
this.value = value;
}
public String toString() {
return value;
}
}
(2)NoFoundExcepiton.java类
package com.liyan.exception;
/**
* 自定义No Found异常
* Title: NoFoundExcepiton
* @author Liyan
* @date 2018年1月11日 下午3:36:13
*/
public class NoFoundExcepiton extends Exception {
private static final long serialVersionUID = -5955607821816077172L;
public NoFoundExcepiton(String errorInfo) {
super(errorInfo);
}
}
(3)GlobalExceptionHandler.java全局异常类
package com.liyan.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.liyan.model.ResponseResult;
@CrossOrigin
@RestControllerAdvice
public class GlobalExceptionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler
public ResponseResult processException(Exception ex, HttpServletRequest request, HttpServletResponse response){
ex.printStackTrace();
if(ex instanceof MissingServletRequestParameterException){
return new ResponseResult(400, ex.getMessage(), null);
}
if(ex instanceof NoFoundExcepiton){
LOGGER.error("======="+ex.getMessage()+"=======");
return new ResponseResult(401, "无法找到相应数据!", null);
}
return new ResponseResult(500, ex.getMessage(), null);
}
}
7.在com.liyan.controller包下创建
(1)创建UserController.java类
package com.liyan.controller;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.liyan.exception.ExceptionEnum;
import com.liyan.exception.NoFoundExcepiton;
import com.liyan.model.User;
import com.liyan.service.UserService;
@RestController
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.liyan.model"})//添加的注解
public class UserController {
@Autowired
private UserService userService;
/**
* 引入日志,注意都是"org.slf4j"包下
*/
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
/**
* 根据员工工号,查询员工
* Title: selectUser
* @author Liyan
* @date 2018年1月11日 上午11:37:46
* @param userId 员工工号
* @param httpServletResponse
* @return User
* @throws Exception
*/
@RequestMapping(value = "selectUser/{userId}",method = RequestMethod.GET)
public User selectUser(@PathVariable String userId, HttpServletResponse httpServletResponse) throws Exception {
User user = userService.selectUser(userId);
logger.info("访问selectUser/{userId}接口,参数userId = " + "userId");
if (user == null) {
logger.error("根据员工工号,查询员工异常:e=" + ExceptionEnum.ERROR_NOFOUND.getValue());
throw new NoFoundExcepiton(ExceptionEnum.ERROR_NOFOUND.getValue());
}
return user;
}
}
(2)创建UserController.java启动类
package com.liyan.controller;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 启动类
* Title: SpringbootApplication
* @author Liyan
* @date 2018年1月11日 上午11:36:48
*/
@SpringBootApplication(scanBasePackages = {"com.liyan"})
@MapperScan("com.liyan.mapper")
@EnableTransactionManagement//开启事务管理
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
8.配置文件相关
(1)application.properties
#============ 数据库配置#======================================
spring.datasource.url=jdbc:mysql://127.0.0.1:3306?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
#用户名和密码
spring.datasource.username=记得换成自己的
spring.datasource.password=记得换成自己的
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database=记得换成自己的
#============ tomcat配置#====================================
server.port=80
#============ mybatis配置 ====================================
#起别名。可省略写mybatis的xml中的resultType的全路径
mybatis.type-aliases-package=com.liyan.model
#Mybatis扫描(配置xml模式使用)
mybatis.mapper-locations=classpath*:mapper/*.xml
#=========== 日志配置·简易(spring boot已经集成logback日志)=========
#controller层日志 WARN级别输出
#logging.level.com.liyan.controller=WARN
#mapper层 sql日志 DEBUG级别输出
#logging.level.com.liyan.mapper=DEBUG
#logging.file=logs/spring-boot-logging.log
#logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
#logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
#打印运行时sql语句到控制台
#spring.jpa.show-sql=true
#==================== 日志配合·标准 ============================
logging.config=classpath:logback-boot.xml
(2)logback-boot.xml 日志配置文件(重点)
%d %p (%file:%line\)- %m%n
UTF-8
log/demo.log
log/demo.%d.%i.log
30
1KB
%d %p (%file:%line\)- %m%n
UTF-8
9.创建数据库表结构,建表语句如下,数据自己随便加吧
CREATE TABLE `user_tab` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` VARCHAR(10) NOT NULL,
`user_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`) USING BTREE
) ENGINE=INNODB DEFAULT CHARSET=utf8
10.启动
11.访问:http://localhost/selectUser/G353 (多刷新几次,看日志效果)如下:
demo.log一旦大于刚刚配置的1kb,立即会被分割成按日期命名的各个小日志。