2小时学会spring boot 以及spring boot进阶之web进阶(已完成)

1:更换Maven默认中心仓库的方法

<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>

2:相关代码

如果要用到view页面需要引入

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> 用数据库和jpa需要引入以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>

@RestController//返回json,@Controller返回view    @RestController等同于@Controller和@ResponseBody
@RequestMapping("/hello") // 可以省略
public class HelloController {

@value("${mytest}")

private string test;

//上面同下面两种方式注入配置

@Autowired
private GirlProperties girlProperties;

@RequestMapping(value="say",method = RequestMethod.GET)
public String say(){
return girlProperties.getCupSize();
// return "index";//配合@Controller使用返回view
}

// @RequestMapping(value={"/sayy","sayy2"},method = RequestMethod.GET)
@GetMapping(value="/sayy")
public String sayy(@RequestParam(value="id",required = false,defaultValue = "0") Integer myId){
return "id:"+myId;
}

@GetMapping(value="/girls/{id}")
public Girl getGirlById(@PathVariable("id") Integer id){
return girlRepository.findOne(id);
}


}

@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {

private String cupSize;

private Integer age;

public String getCupSize() {
return cupSize;
}

public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

配置文件如下

girl:
cupSize: B
age: 18
mytest:ccctest
content:"zhangsansan ${name}+${age}"
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/boot
username: root
password: root5770
jpa:
hibernate:
ddl-auto: update
show-sql: true

3:   springboot 启动方式

1:右键启动MyspringbootApplication

2:命令行启动mvn spring-boot:run

3:先mvn install 然后 java -jar xxx.jar --spring.profiles.active=prod

4:server.context-path=/girl 设置通用路径

5:设置不同的配置环境文件

spring:
   profiles:
     active: dev

6:jpa相关代码

@Entity
public class Girl {

@Id
@GeneratedValue
private Integer id;

private String cupSize;

private Integer age;
}

public interface GirlRepository extends JpaRepository<Girl,Integer>{

public List<Girl> findByAge(Integer age);
}

7: spring aop 是一种编程范式与语言无关

需要引入

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

@Aspect
@Component
public class HttpAspect {

private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

@Pointcut("execution(public * com.imooc.controller.GirlController.*(..))")
public void log() {
}

@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();

//url
logger.info("url={}", request.getRequestURL());

//method
logger.info("method={}", request.getMethod());

//ip
logger.info("ip={}", request.getRemoteAddr());

//类方法
logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

//参数
logger.info("args={}", joinPoint.getArgs());
}

@After("log()")
public void doAfter() {
logger.info("222222222222");
}

@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
logger.info("response={}", object.toString());
}

}

也可以用一下方式代替不用设置pointcut

@After("execution(public * com.imooc.controller.GirlController.*(..))")
public void doAfter() {
logger.info("222222222222");
}

8:@Valid注解用于校验,所属包为:javax.validation.Valid。

① 首先需要在实体类的相应字段上添加用于充当校验条件的注解,如:@Min,如下代码(age属于Girl类中的属性):

@Min(value = 18,message = "未成年禁止入内")
private Integer age;
② 其次在controller层的方法的要校验的参数上添加@Valid注解,并且需要传入BindingResult对象,用于获取校验失败情况下的反馈信息,如下代码:
@PostMapping("/girls")
public Girl addGirl(@Valid Girl girl, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
return girlResposity.save(girl);
}
bindingResult.getFieldError.getDefaultMessage()用于获取相应字段上添加的message中的内容,如:@Min注解中message属性的内容

9:全局异常捕获

@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 GirlException) {
GirlException girlException = (GirlException) e;
return ResultUtil.error(girlException.getCode(), girlException.getMessage());
}else {
logger.error("【系统异常】{}", e);
return ResultUtil.error(-1, "未知错误");
}
}
}

10:异常类

public class GirlException extends RuntimeException{

    private Integer code;

    public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
} public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
}
} 调用方法

public void getAge(Integer id) throws Exception{
Girl girl = girlRepository.findOne(id);
Integer age = girl.getAge();
if (age < 10) {
//返回"你还在上小学吧" code=100
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if (age > 10 && age < 16) {
//返回"你可能在上初中" code=101
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}

}


11:枚举类
public enum ResultEnum {
UNKONW_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;
}
}
12:http请求返回的最外层对象

public class Result<T> {

/** 错误码. */
private Integer code;

/** 提示信息. */
private String msg;

/** 具体的内容. */
private T data;

}

13:封装返回对象方法

public class ResultUtil {

public static Result success(Object object) {
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
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.setCode(code);
result.setMsg(msg);
return result;
}
}

14:单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest { @Autowired
private GirlService girlService; @Test
public void findOneTest() {
Girl girl = girlService.findOne(73);
Assert.assertEquals(new Integer(13), girl.getAge());
}
} 15:测试controller
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GirlControllerTest { @Autowired
private MockMvc mvc; @Test
public void girlList() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));
} }
16:事务控制
@Transactional
@Override
public void saveTwo() {
Girl girlA = new Girl();
girlA.setAge(18);
girlA.setCupSize("A");
girlRepository.save(girlA); Girl girlB = new Girl();
girlB.setAge(19);
girlB.setCupSize("B");
girlRepository.save(girlB); }
上一篇:数据挖掘(data mining),机器学习(machine learning),和人工智能(AI)的区别是什么? 数据科学(data science)和商业分析(business analytics)之间有什么关系?


下一篇:[转自知乎] 从github上下载单个文件夹