学习完毕

This commit is contained in:
F嘉阳
2018-01-30 15:47:49 +08:00
parent ada1645637
commit a08d60d77b
24 changed files with 688 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

107
pom.xml Normal file
View File

@@ -0,0 +1,107 @@
<?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.fjy</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot</name>
<description>Learn project for Spring Boot Base</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M7</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>
<version>1.5.9.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

@@ -0,0 +1,12 @@
package com.fjy.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}

View File

@@ -0,0 +1,43 @@
package com.fjy.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 logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.fjy.springboot.controller.PersonController.*(..))")
public void log(){
}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
logger.info("请求执行PersonController");
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("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
logger.info("args={}",joinPoint.getArgs());
//System.out.println("请求执行PersonController");
}
@After("log()")
public void doAfter(){
logger.info("结束对PersonController的请求");
//System.out.println("结束对PersonController的请求");
}
@AfterReturning(returning = "object",pointcut = "log()")
public void doAfterReturning(Object object){
logger.info("response={}",object.toString());
}
}

View File

@@ -0,0 +1,38 @@
package com.fjy.springboot.controller;
import com.fjy.springboot.properties.PersonProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
@RestController
public class HelloController {
/**
* 从yml配置文件注入
*/
@Value("${content}")
private String content;
/**
* 按组注入,推荐
*/
@Autowired
private PersonProperties personProperties;
@RequestMapping(value = {"/hello"},method = RequestMethod.GET)
public String say(){
// return content;
return personProperties.toString();
}
@RequestMapping(value = {"/tell/{id}"},method = RequestMethod.POST)
public String tell(@PathVariable("id") Integer id){
// return content;
return "id="+id;
}
//@RequestMapping(value = {"/tell"},method = RequestMethod.POST)
//@GetMapping("/tell")
@PostMapping("/tell")
public String tellParam(@RequestParam(value = "id",required = false,defaultValue = "0") Integer param){
// return content;
return "id="+param;
}
}

View File

@@ -0,0 +1,13 @@
package com.fjy.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class LoginController {
@GetMapping("/login")
public String doLogin(){
return "/index";
}
}

View File

@@ -0,0 +1,34 @@
package com.fjy.springboot.domain;
/**
* Http请求返回的最外层对象
*/
public class Result<T> {
private Integer code;//错误码
private String message;//错误信息
private T data;//具体内容
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@@ -0,0 +1,70 @@
package com.fjy.springboot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;
@Entity
public class person {
/**
* 加入主键和自增的注解,用于自动建表
*/
@Id
@GeneratedValue
private Integer id;
private String name;
@Min(value = 0,message = "年龄必须大于0")
private Integer age;
private String content;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getContent() {
return content;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", content='" + content + '\'' +
'}';
}
/**
* 必须显示指定空的构造方法
*/
public person() {
}
}

View File

@@ -0,0 +1,25 @@
package com.fjy.springboot.enums;
public enum ResultEnum {
UNKNOW_ERROR(-1,"未知错误"),
SUCCESS(0,"成功"),
PRIMARY_SCHOOL(100,"小学生~"),
MIDDLE_SCHOOL(101,"中学生!")
;
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;
}
}

View File

@@ -0,0 +1,21 @@
package com.fjy.springboot.exception;
import com.fjy.springboot.enums.ResultEnum;
public class PersonException extends RuntimeException {
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;
}
}

View File

@@ -0,0 +1,32 @@
package com.fjy.springboot.handle;
import com.fjy.springboot.exception.PersonException;
import com.fjy.springboot.domain.Result;
import com.fjy.springboot.untils.ResultUtil;
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 final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)//指定捕获的异常类
@ResponseBody//统一返回json格式
public Result handle(Exception e){
if (e instanceof PersonException){
PersonException personException = (PersonException)e;
return ResultUtil.error(personException.getCode(),personException.getMessage());
}else {
logger.error("系统异常{}",e);
return ResultUtil.error(-1,"未知错误");
}
}
}

View File

@@ -0,0 +1,47 @@
package com.fjy.springboot.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "person")
public class PersonProperties {
private String name;
private Integer age;
private String content;
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getContent() {
return content;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "PersonProperties{" +
"name='" + name + '\'' +
", age=" + age +
", content='" + content + '\'' +
'}';
}
}

View File

@@ -0,0 +1,13 @@
package com.fjy.springboot.repository;
import com.fjy.springboot.domain.person;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PersonRepository extends JpaRepository<person,Integer> {
/**
* 继承jpa泛型为类名和主键类型
*/
public List<person> findByAge(Integer age);
}

View File

@@ -0,0 +1,37 @@
package com.fjy.springboot.service;
import com.fjy.springboot.enums.ResultEnum;
import com.fjy.springboot.exception.PersonException;
import com.fjy.springboot.domain.person;
import com.fjy.springboot.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public void getAge(Integer id)throws Exception{
Optional opt = personRepository.findById(id);
person per = (person)opt.get();
Integer age = per.getAge();
if (age < 10){
throw new PersonException(ResultEnum.PRIMARY_SCHOOL);
}else if(age>10&&age <16) {
throw new PersonException(ResultEnum.MIDDLE_SCHOOL);
}
}
/**
* 通过ID查一个人
* @param id
* @return
*/
public person findOne(Integer id){
return personRepository.findById(id).get();
}
}

View File

@@ -0,0 +1,30 @@
package com.fjy.springboot.untils;
import com.fjy.springboot.domain.Result;
public class ResultUtil {
public static Result success(Object object){
Result result = new Result();
result.setMessage("成功");
result.setCode(0);
result.setData(object);
return result;
}
public static Result success(){
return success(null);
}
public static Result error(Integer code,String msg){
Result result = new Result();
result.setMessage("失败");
result.setCode(code);
result.setData(msg);
return result;
}
public static Result info(Integer code,String msg){
Result result = new Result();
result.setMessage("提示");
result.setCode(code);
result.setData(msg);
return result;
}
}

View File

@@ -0,0 +1,25 @@
#开发环境配置文件
server:
servlet:
context-path: /spring
port: 8080
name: fjy
age: 18
content: "My name is ${name},age ${age}!"
person:
name: fjy8018
age: 18
content: Spring Boot!
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_school?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: vantenuser
password: vanten
jpa:
hibernate:
ddl-auto: update
show-sql: true
debug: true

View File

@@ -0,0 +1,13 @@
#运行环境配置文件
server:
servlet:
context-path: /spring
port: 8080
name: fjy
age: 20
content: "My name is ${name},age ${age}!"
person:
name: fjy8018
age: 20
content: Spring Boot

View File

@@ -0,0 +1 @@
#server.servlet.context-path=/spring

View File

@@ -0,0 +1,4 @@
#控制配置文件调用
spring:
profiles:
active: dev

View File

@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h1>登录页面</h1>
</body>
</html>

View File

@@ -0,0 +1,28 @@
package com.fjy.springboot;
import com.fjy.springboot.domain.person;
import com.fjy.springboot.service.PersonService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 单元测试类
* 加入注解表示要在测试环境中运行
* 第二个表示启动整个Spring工程
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private PersonService personService;
@Test
public void findOneTest(){
person per = personService.findOne(8);
Assert.assertEquals(new Integer(14),per.getAge());//断言,写入期望值
}
}

View File

@@ -0,0 +1,16 @@
package com.fjy.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@@ -0,0 +1,30 @@
package com.fjy.springboot.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.junit.Assert.*;
/**
* API测试控制类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void personList()throws Exception {
//mvc.perform(MockMvcRequestBuilders.get("/persons")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string(""));
}
}

View File

@@ -0,0 +1,15 @@
package com.fjy.springboot.service;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* IDEA自动生成的测试类
*/
public class PersonServiceTest {
@Test
public void findOne() {
}
}