1.依赖 pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</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-configuration-processor</artifactId> <optional>true</optional> </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> </dependencies>
2Spring Boot 的配置文件
1. spring boot有两种格式配置文件:1.application.properties 传统的key/value配置
2.application.yml 分支配置
不同环境不同配置的切换:
properties-dev是开发环境
properties-prod是生产环境
开发环境可以在application.peoperties中加入以下配置:
生产环境:
2.项目相关配置
server.port=8081
切换端口,默认端口是8080
server.servlet.path=/employee
切换根路径
3.spring boot配置加载类
@SpringBootApplication public class EmployeeApplication { public static void main(String[] args) { SpringApplication.run(EmployeeApplication.class, args); } }
默认加载了application.properties/application.yml中的配置
如果pom.xml中有jpa和mysql的依赖,那么会加载默认的数据源,如果在application.propeties没有配置则会报错;
如果不用配置源:则可以在主配置类上添加
@EnableAutoConfiguration
[email protected]注解的使用
在配置文件中定义:cupSize=F
在类中可以通过@Value取得
@Value("{cupSize}") private String cupSize;
并且不用考虑常用类型转换:
age=10
@Value("{age}") private Integer age;
5.自动把配置文件的value注入到实体类
package com.victor.employee.pojo; import org.springframework.boot.context.properties.ConfigurationProperties; @component @ConfigurationProperties(prefix = "gril") public class Gril { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
@ConfigurationProperties(prefix = "gril")
该注解把配置文件中girl的属性注入到实体中
@Component
实例化实体bean
application。properties:
gril.name=yin gril.age=18
使用@autowired加载使用
@Autowired private Gril gril;
6.Controller中注解
package com.victor.employee.Controller; import com.victor.employee.pojo.Employee; import com.victor.employee.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; @RestController public class EmployeeController { @Autowired private Employee employee; @Autowired private EmployeeService employeeService; @RequestMapping(value = "/hello",method = RequestMethod.GET) public String hello(){ return "hello world"+employee.getName(); } @RequestMapping(value = "/findall",method = RequestMethod.GET) public List<Employee> findAll(){ return employeeService.findAll(); } @RequestMapping(value = "/insert",method = RequestMethod.POST) public Employee insert(@Valid Employee employee, BindingResult result) { if (result.hasErrors()) { System.out.print(result.getFieldError().getDefaultMessage()); return null; } return employeeService.save(employee); } }
@RestController是俩个注解的合并
@Controller
@ResponseBody
@RequesMapping定义访问路径;用在类上为二级目录;方法上为方法路径
参数:
value:指定路径
method:指定那种方法可以访问post还是get等
获取路径中的参数@PathVariable
@RequestMapping(value = "/hello/{id}",method = RequestMethod.GET) public String hello(@PathVariable("id")Integer id){ return "hello world"+employee.getName()+id; }
获取localhost:8080/hello?id=10这样的的参数并制定默认值@RequestParam
public String hello(@RequestParam(value="id" ,required = false,defaultValue ="1") Integer id){ return "hello world"+employee.getName()+id; }
7.数据库的操作
配置数据源
spring.datasource.url=jdbc:mysql://localhost/dbgirl spring.datasource.username=root spring.datasource.password=luohao310545 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
建立实体类Employee
package com.victor.employee.pojo; import org.springframework.stereotype.Component; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.Min; /** * 实体类 */ @Entity//声明该类是一个实体 @Component//自动生成bean public class Employee { @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 String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Employee() { } @Override public String toString() { return "Employee{" + "id=" + id + ", name=‘" + name + ‘\\‘‘ + ", age=" + age + ‘}‘; } }
建立dao接口并继承JpaRepository接口
EmployeeDao
package com.victor.employee.dao; import com.victor.employee.pojo.Employee; import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeeDao extends JpaRepository<Employee,Integer> { }
建立service接口与实现
EmployeeService ...
EmployeeServiceImpl
package com.victor.employee.service.Impl; import com.victor.employee.common.Const; import com.victor.employee.common.RestResult; import com.victor.employee.dao.EmployeeDao; import com.victor.employee.exception.LocalException; import com.victor.employee.pojo.Employee; import com.victor.employee.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; @Service("employeeService") @Transactional public class EmployeeServiceImpl implements EmployeeService{ @Autowired private EmployeeDao employeeDao; public List<Employee> findAll(){ return employeeDao.findAll(); } public Employee save(Employee employee){ return employeeDao.save(employee); } public RestResult<String> getEmployee(Integer id)throws Exception{ Employee employee=employeeDao.getOne(id); Integer age=employee.getAge(); if(age<10){ throw new LocalException(Const.ExceptionCode.YEARSUP.getCode(),Const.ExceptionCode.YEARSUP.getMsg()); } else if(age<15&&age>10){ throw new LocalException(Const.ExceptionCode.YEARSBELONG.getCode(),Const.ExceptionCode.YEARSBELONG.getMsg()); } return RestResult.createBySuccess(); } }
通过实例化对象emloyee实现持久化的操作
8.同一日志处理
建立Aspect的处理类
package com.victor.employee.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.ServletRequest; import javax.servlet.http.HttpServletRequest; @Aspect @Component public class HttpAspect { private final static Logger logger= LoggerFactory.getLogger(HttpAspect.class); @Pointcut("execution(public * com.victor.employee.Controller.EmployeeController.findAll(..))") public void log(){ } @Before("log()") public void logbefore(JoinPoint joinPoint){ ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request=attributes.getRequest(); logger.info("url={}",request.getRequestURL()); logger.info("method{}",request.getMethod()); logger.info("ip={}",request.getRemoteAddr()); logger.info("classmethod={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()); logger.info("args={}",joinPoint.getArgs()); } @After("log()") public void logafter(){ System.out.print(2222222); } @AfterReturning(returning = "object",pointcut = "log()") public void doAfterReturning(Object object){ logger.info("respond={}",object); } }
9.统一的异常处理
a.建立高可用的Rest接口类
RestResult‘
package com.victor.employee.common; public class RestResult<T> { private Integer code; private String msg; private T data; private RestResult(){}; private RestResult(Integer code){ this.code=code; } private RestResult(Integer code,String msg){ this.code=code; this.msg=msg; } private RestResult(Integer code,T data){ this.code=code; this.data=data; } private RestResult(Integer code,String msg,T data){ this.code=code; this.msg=msg; this.data=data; } public boolean isSuccess(){ return this.code==RestResultEnum.SUCCESS.getCode(); } public static <T>RestResult<T> createBySuccess(){ return new RestResult<T>(RestResultEnum.SUCCESS.getCode()); } public static <T>RestResult<T> createBySuccess(String msg){ return new RestResult<T>(RestResultEnum.SUCCESS.getCode(),msg); } public static <T>RestResult<T> createBySuccess(String msg,T data){ return new RestResult<T>(RestResultEnum.SUCCESS.getCode(),msg,data); } public static <T>RestResult<T> createBySuccess(T data){ return new RestResult<T>(RestResultEnum.SUCCESS.getCode(),data); } public static <T>RestResult<T> createByError(){ return new RestResult<T>(RestResultEnum.FAILED.getCode(),RestResultEnum.FAILED.getMsg()); } public static <T>RestResult<T> createByError(String errorMsg){ return new RestResult<T>(RestResultEnum.FAILED.getCode(),errorMsg); } public static <T>RestResult<T> createByError(int errorCode,String errorMsg){ return new RestResult<T>(errorCode,errorMsg); } 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; } }
RestResultEnum
package com.victor.employee.common; public enum RestResultEnum { SUCCESS(1,"success"), FAILED(0,"failed"); private int code; private String msg; public int getCode() { return code; } public String getMsg() { return msg; } RestResultEnum(int code, String msg) { this.code = code; this.msg = msg; } }
建立自己异常类
LocalException:
package com.victor.employee.exception; public class LocalException extends RuntimeException { private Integer code; public LocalException(int code,String msg){//还可以添加一个枚举对象 super(msg); this.code=code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
建立异常 处理类
ExceptionHandle:
package com.victor.employee.exception; import com.victor.employee.common.RestResult; 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; @ControllerAdvice public class ExceptionHandle { private Logger logger= LoggerFactory.getLogger(ExceptionHandle.class); @ResponseBody @ExceptionHandler(value= Exception.class) public RestResult handle(Exception e){ if(e instanceof LocalException){ LocalException localException=(LocalException)e; return RestResult.createByError(localException.getCode(),localException.getMessage()); } logger.info("系统异常",e); return RestResult.createByError(-1,"位置错误"); } }
常量类:
package com.victor.employee.common; /** * 常量类 */ public class Const { public enum ExceptionCode{ UNKNOWEXCEPTION(-1,"未知错误"), SUCCESS(1,"成功"), YEARSBELONG(100,"15以上"), YEARSUP(101,"10岁以下"); private int code; private String msg; private ExceptionCode(int code,String msg){ this.code=code; this.msg=msg; } public int getCode() { return code; } public String getMsg() { return msg; } } }