SpringBoot - 初识
软件152 尹以操
一、SpringBoot使用起来比起SpringMVC更便捷,在注解上的小变化,我记录了下面几个:
@Controller + @ResponseBody = SpringMVC中用@RestController来代替前面两个注解,通过这个注解,可以将所有的前端http请求放入SpringBoot的Controller容器中,并返回json格式的数据给前端 @RequestMapping(value={"/hello","/hi"},method=RequestMethod.GET) = @GetMapping(value={"/hello","/hi"}),在请求的注解上也有变化,例如例子的用Get请求方式可以直接变成@GetMapping(value={"/hello","/hi"}),当然Post请求就可以是@PostMapping等等。
@...Mapping(value="personDelete/{id}") ----->@PathVariable("id") Integer id 在请求的方法名的参数前写@PathVariable可以获取到请求链接中的参数,如请求http://localhost:8080/personDelete/1024,可以获取到id的值为1024
@...Mapping(value="findByName") ------> @RequestParam(value="name",required=false) String name 同样,可以通过@RequestParam来获取请求发过来的参数,value值就是要获取的参数的name
二、SpringBoot可以直接对操作数据库中的值进行验证,如:
表单验证 @Min(value=18,message="未成年") 加在实体Entity类的属性上,表示获取的值最小为18 @Valid Person person,BindingResult bindingResult Controller的 某一个方法上(作为参数),验证结果保存在BindingResult里可通过下面的方法来获取 if(bindingResult.hasErrors()){ System.out.println(bindingResult.getFieldError().getDefaultMessage());//获取到错误信息 ,当然,也可以返回给前端去,这里获取的值就是“未成年” return null; }
三、SpringBoot的AOP也是挺好用的,通过我对Spring的了解,似乎SpringBoot和Spring的AOP差不多,到底还是一家人儿。
package com.yyc.aspect; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; 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; @Aspect @Component public class HttpAspect { private final static Logger logger= LoggerFactory.getLogger(HttpAspect.class); @Pointcut("execution(public * com.yyc.controller.PersonController.*(..))") public void log(){ } @Before("log()") public void doBefore(JoinPoint joinPoint){ //可以获取到前端发送请求时的一些参数 // logger.info("1111111111"); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request=attributes.getRequest(); //url logger.info("url={}",request.getRequestURI()); //method logger.info("method={}",request.getMethod()); //ip logger.info("ip={}",request.getRemoteAddr()); //类方法 logger.info("classMethod={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()); //参数 logger.info("args={}",joinPoint.getArgs()); } @After("log()") public void doAfter(){ logger.info("2222222222"); } @AfterReturning(returning="object",pointcut="log()") public void doAfterReturning(Object object){//也可以获取到前端请求后,SpringBoot返回给客户端的一些数据 logger.info("response={}",object.toString()); } }
四、在SpringBoot中同样可以对异常信息进行统一处理,比如,我们有一些方法执行后要给客户端返回一些必要的信息,但是呢,这些信息不统一,很分散,可能对不同的结果返回不同的值,这时候统一异常处理就派上用场了,这样类处理就比较方便了。比如这个方法:
public void getAge(Integer id) throws Exception{ Person person = personRepository.findOne(id); Integer age=person.getAge(); if(age < 10 ){ //返回 你还在上小学吧 throw new PersonException(ResultEnum.PRIMARY_SCHOOL);//这里用了一个自定义异常,用到枚举来对返回的东西进行封装 }else if(age >= 10&& age<=16){ //返回 你可能还在上初中 throw new PersonException(ResultEnum.MIDDLE_SCHOOL); } }
自定义异常类来捕获异常,注意要继承RuntimeException :
package com.yyc.exception; import com.yyc.enums.ResultEnum; public class PersonException extends RuntimeException { private static final long serialVersionUID = 1L; private Integer code; public PersonException(ResultEnum resultEnum) { super(resultEnum.getMsg()); this.code=resultEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
异常的统一管理(照我的理解,就是可以通过这个类来对异常进行统一管理,当产生异常可以返回给客户端json数据):
package com.yyc.handle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import com.yyc.entity.Result; import com.yyc.exception.PersonException; import com.yyc.utils.ResultUtil; @ControllerAdvice public class ExceptionHandle { private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value=Exception.class) @ResponseBody public Result<?> handle(Exception e){ if(e instanceof PersonException){ return ResultUtil.error(((PersonException) e).getCode(), e.getMessage()); }else{ logger.error("【系统异常】{}",e); return ResultUtil.error(-1, "内置错误"); } } }
五、我们知道,客户端请求,希望的是要我们服务端返回一个固定的json格式,方便解析,一个Result类可以对返回的数据的数据格式定义:
package com.yyc.entity; public class Result<T> { 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; } }
前面有调用的ResultUtil类,这个类对上面的Result类进行使用和封装,以便其它地方调用:
package com.yyc.utils; import com.yyc.entity.Result; public class ResultUtil { public static Result success(Object obj){ Result result=new Result(); result.setCode(1); result.setMsg("成功"); result.setData(obj); return result; } public static Result success(){ return success(null); } public static Result error(Integer code,String msg){ Result result=new Result(); result.setCode(0); result.setMsg(msg); result.setData(null); return result; } }
六、SpringBoot中没有xml来配置,默认用properties文件来配置,但是建议用yml文件配置:
application.yml:
spring:
profiles:
active: dev 就像html中的include一样,可以通过spring profiles active来激活或导入另一个yml文件,如:application-dev.yml
//对数据库的一些配置
datasource:
username: root
password: 123
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
hibernate:
ddl-auto: update
show-sql: true
七、maven的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.yyc</groupId> <artifactId>springboot_1</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>springboot_1</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.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-thymeleaf</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency><!--springBoot的热部署插件,devtools,加入这个可以不用每次修改代码重启服务--> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
好了,这就是这两天看springboot的一些收获了吧。就小记一下。