pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bxw</groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!-- 如果没有该项配置,devtools不会起作用,即应用不会restart --> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>
application.yml
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/spring
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
application-dev.yml
server:
port: 8888
context-path: /springboot
user:
username: bxw
password: bxw123
content: "username:${name} password:${psd}"
author: bxw
application-prod.yml
server:
port: 8000
context-path: /springboot
user:
username: haha
password: haha123
content: "username:${name} password:${psd}"
author: haha
entity:
实体类Girl.java,这里包含了springboot中表单验证的举例,@Min验证最小值
package com.bxw.springboot.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.Min; @Entity public class Girl { @Id @GeneratedValue private Integer id; private String name; @Min(value = 18,message = "未成年少女禁止") private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
controller
GIrlController.java
package com.bxw.springboot.controller; import com.bxw.springboot.dao.GirlDao; import com.bxw.springboot.entity.Girl; import com.bxw.springboot.entity.Result; import com.bxw.springboot.enums.ResultEnum; import com.bxw.springboot.service.GirlService; import com.bxw.springboot.utils.ResultUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController() @RequestMapping("/girl") public class GirlController { @Autowired private GirlDao girlDao; @Autowired private GirlService girlService; /** * 找到所有的女生 * @return */ @GetMapping("/list") public List<Girl> FindGirlList(){ return girlDao.findAll(); } /** * 通过年龄查询 * @param age * @return */ @GetMapping("/byAge/{age}") public List<Girl> findByAge(@PathVariable("age") Integer age){ return girlDao.findByAge(age); } /** * 更新 * @param id * @param name * @param age * @return */ @GetMapping("/update") public Girl updateGirl(@RequestParam("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age){ Girl girl = new Girl(); girl.setId(id); girl.setName(name); girl.setAge(age); return girlDao.save(girl); } /** * 增加一个妹子 * @return */ @GetMapping("/add") //public Girl addGirl(@RequestParam("name") String name, // @RequestParam("age") Integer age){ public Result addGirl(@Valid Girl girl, BindingResult bindingResult){ if(bindingResult.hasErrors()){//如果验证的结果错误,打印信息 // return ResultUtil.failed(null); return null; } // Girl girl = new Girl(); // girl.setName(name); // girl.setAge(age); return ResultUtil.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),girlDao.save(girl)); } @GetMapping("/del/{id}") public void delGirl(@PathVariable("id") Integer id){ girlDao.delete(id); } @GetMapping("/find/{id}") public Girl findGirl(@PathVariable("id") Integer id){ return girlService.findByAge(id); } }
=================================================统一日志处理=========================================================
Aop
HttpAspect.java
package com.bxw.springboot.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Aspect @Component public class HttpAspect { private final static Logger log = LoggerFactory.getLogger(HttpAspect.class); @Pointcut("execution(public * com.bxw.springboot.controller.GirlController.*(..))") public void log(){ } @Before("log()") public void doBefore(JoinPoint jp){ log.info("this is doBefore method"); ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //url log.info("url={}",request.getRequestURL()); //method log.info("method={}",request.getMethod()); //ip log.info("ip={}",request.getRemoteAddr()); //类方法 log.info("class_method={}",jp.getSignature().getDeclaringTypeName()+"."+jp.getSignature().getName()); //参数 log.info("args={}",jp.getArgs()); } @After("log()") public void doAfter(){ log.info("this is doAfter method"); } /* @Around("log()") public void doAround(ProceedingJoinPoint pjp){ log.info("start doAround method"); try { pjp.proceed(); }catch (Throwable e){ e.printStackTrace(); } log.info("end doAround method"); } */ @AfterReturning(returning = "obj",pointcut = "log()") public void doAfterReturning(Object obj){ log.info("obj={}",obj.toString()); } }
=====================================================统一异常处理:=========================================================
先定义一个封装异常的实体类Result.java
package com.bxw.springboot.entity; public class Result<T> { /** 状态码.{0:失败,1:成功} */ private Integer code; /** 提示信息.*/ private String msg; /** 具体的内容. */ private T 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 T getData() { return data; } public void setData(T data) { this.data = data; } }
枚举定义异常类型ResultEnum.java
package com.bxw.springboot.enums; public enum ResultEnum { UKNOWN_ERROR(-1,"未知错误"), SUCCESS(1,"成功"), failed(0,"失败"), ; private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } }
定义工具类:ResultUtil.java
package com.bxw.springboot.utils; import com.bxw.springboot.entity.Result; public class ResultUtil { /** * 请求成功 * @param obj * @return */ public static Result success(Integer code,String msg,Object obj){ Result result = new Result(); result.setCode(code); result.setMsg(msg); result.setData(obj); return result; } /** * 请求失败 * @param obj * @return */ public static Result failed(Integer code,String msg,Object obj){ Result result = new Result(); result.setCode(code); result.setMsg(msg); result.setData(obj); return result; } }
自定义异常GirlException.java
package com.bxw.springboot.Exception; public class GirlException extends RuntimeException{ /** 状态码. */ private Integer code; public GirlException(Integer code,String msg){ super(msg); this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
异常处理类ExceptionHandle.java该类必须放在spring可以扫描到的位置。
package com.bxw.springboot.Handle; import com.bxw.springboot.Exception.GirlException; import com.bxw.springboot.entity.Result; import com.bxw.springboot.enums.ResultEnum; import com.bxw.springboot.utils.ResultUtil; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public Result handle(Exception e){ if(e instanceof GirlException){ GirlException girlException = (GirlException)e; return ResultUtil.failed(girlException.getCode(),girlException.getMessage(),null); }else{ return ResultUtil.failed(ResultEnum.UKNOWN_ERROR.getCode(),ResultEnum.UKNOWN_ERROR.getMsg(),null); } } }
@ExceptionHandler统一处理某一类异常