這次的學習以一個簡單的Student Demo為示例。 1、代碼: 主程式類DemoApplication.java。 1 package com.julion.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import ...
這次的學習以一個簡單的Student Demo為示例。
1、代碼:
主程式類DemoApplication.java。
1 package com.julion.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 @SpringBootApplication 7 public class DemoApplication { 8 9 public static void main(String[] args) { 10 11 SpringApplication.run(DemoApplication.class, args); 12 13 } 14 }View Code
實體類Student.java。
1 package com.julion.demo.domain; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.validation.constraints.Min; 7 8 @Entity 9 public class Student { 10 11 @Id 12 @GeneratedValue 13 private int id; 14 15 @Min(value = 10, message = "未滿10歲不來塞") 16 private int age; 17 18 private String name; 19 20 public Student(){ 21 22 } 23 24 public int getId() { 25 return id; 26 } 27 28 public void setId(int id) { 29 this.id = id; 30 } 31 32 public int getAge() { 33 return age; 34 } 35 36 public void setAge(int age) { 37 this.age = age; 38 } 39 40 public String getName() { 41 return name; 42 } 43 44 public void setName(String name) { 45 this.name = name; 46 } 47 }View Code
結果類Result.java。
1 package com.julion.demo.domain; 2 3 public class Result<T> { 4 5 private int code; 6 7 private String message; 8 9 private T data; 10 11 public int getCode() { 12 return code; 13 } 14 15 public void setCode(int code) { 16 this.code = code; 17 } 18 19 public String getMessage() { 20 return message; 21 } 22 23 public void setMessage(String message) { 24 this.message = message; 25 } 26 27 public T getData() { 28 return data; 29 } 30 31 public void setData(T data) { 32 this.data = data; 33 } 34 }View Code
數據相關類StudentRepository.java。
1 package com.julion.demo.repository; 2 3 import com.julion.demo.domain.Student; 4 import org.springframework.data.jpa.repository.JpaRepository; 5 6 import java.util.List; 7 8 public interface StudentRepository extends JpaRepository<Student, Integer> { 9 10 public List<Student> findByAge(int age); 11 12 }View Code
控制類StudentController.java。
1 package com.julion.demo.controller; 2 3 import com.julion.demo.domain.Result; 4 import com.julion.demo.domain.Student; 5 import com.julion.demo.repository.StudentRepository; 6 import com.julion.demo.util.ResultUtil; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.validation.BindingResult; 9 import org.springframework.web.bind.annotation.*; 10 11 import javax.validation.Valid; 12 import java.util.List; 13 14 @RestController 15 public class StudentController { 16 17 @Autowired 18 private StudentRepository studentRepository; 19 20 @GetMapping(value = "/student") 21 public List<Student> getList(){ 22 return studentRepository.findAll(); 23 } 24 25 @PostMapping(value = "/student") 26 public Result<Student> insert(@Valid Student student, BindingResult bindingResult){ 27 if (bindingResult.hasErrors()){ 28 return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage()); 29 } 30 31 return ResultUtil.success(studentRepository.save(student)); 32 } 33 34 @GetMapping(value = "/student/{id}") 35 public Student getOne(@PathVariable("id") int id){ 36 return studentRepository.findOne(id); 37 } 38 39 @PutMapping(value = "/student/{id}") 40 public Student updateOne(@PathVariable("id") int id, 41 @RequestParam("age") int age, 42 @RequestParam("name") String name){ 43 Student student = new Student(); 44 student.setName(name); 45 student.setId(id); 46 student.setAge(age); 47 48 return studentRepository.save(student); 49 } 50 51 @DeleteMapping(value = "/student/{id}") 52 public void deleteOne(@PathVariable("id") int id){ 53 studentRepository.delete(id); 54 } 55 56 @GetMapping(value = "student/age/{age}") 57 public List<Student> getOneByAge(@PathVariable("age") int age){ 58 return studentRepository.findByAge(age); 59 } 60 61 }View Code
AOP相關類HttpAspect.java。
1 package com.julion.demo.aspect; 2 3 4 import com.julion.demo.domain.Student; 5 import org.aspectj.lang.JoinPoint; 6 import org.aspectj.lang.annotation.*; 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9 import org.springframework.stereotype.Component; 10 import org.springframework.web.context.request.RequestContextHolder; 11 import org.springframework.web.context.request.ServletRequestAttributes; 12 13 import javax.servlet.http.HttpServletRequest; 14 15 @Aspect 16 @Component 17 public class HttpAspect { 18 19 private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class); 20 21 @Pointcut("execution(public * com.julion.demo.controller.StudentController.*(..))") 22 public void log(){ 23 } 24 25 @Before("log()") 26 public void doBefore(JoinPoint joinPoint){ 27 logger.info("i am before"); 28 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 29 HttpServletRequest request = attributes.getRequest(); 30 31 //url 32 logger.info("url={}", request.getRequestURL()); 33 34 //method 35 logger.info("method={}", request.getMethod()); 36 37 //ip 38 logger.info("ip={}",request.getRemoteAddr()); 39 40 //類方法 41 logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); 42 43 //參數 44 logger.info("args={}", joinPoint.getArgs()); 45 } 46 47 @After("log()") 48 public void doAfter(){ 49 logger.info("i am after"); 50 } 51 52 @AfterReturning(returning = "object", pointcut = "log()") 53 public void doAfterReturning(Object object){ 54 logger.info("response={}", object.toString()); 55 } 56 57 }View Code
結果工具類ResultUtil.java。
1 package com.julion.demo.util; 2 3 import com.julion.demo.domain.Result; 4 5 public class ResultUtil { 6 7 public static Result success(Object object){ 8 Result result = new Result(); 9 result.setCode(0); 10 result.setMessage("成功"); 11 result.setData(object); 12 return result; 13 } 14 15 public static Result success(){ 16 return success(null); 17 } 18 19 public static Result error(int code, String message){ 20 Result result = new Result(); 21 result.setCode(code); 22 result.setMessage(message); 23 result.setData(null); 24 return result; 25 } 26 27 }View Code
配置文件application.properties。
server.port=8081 server.context-path=/demo spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/dbdemo spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=trueView Code
2、關於註解:
1) @Entity:註明是實體類。
2) @Aspect:註明是切麵。
@PointCut:標註controller的切點。
@Before:在controller切點前進行。
@After:在controller切點後進行。
@AfterReturning:在controller返回後進行。
3) @RestController:註明是controller。與@Controller和@ResponseBody同時註解的功能相當。
@Autowired:註入。
@GetMapping:註明是Get方法。用以查詢。
@PostMapping:註明是Post方法。用以增加。
@PutMapping:註明是Put方法。用以更新。
@DeleteMapping:註明是Delete方法。用以刪除。
@RequestMapping:註明是請求。
@PathVairable:用以獲取形如/xxx/value格式中的value。
@RequestParam:用以獲取形如?key=value中的value。
4) @Service:註明是Service。
@Component:註明是Component。