SpringBoot基础

一、SpringBoot的特点
  1. 化繁为简,简化配置
  2. 备受关注,是下一代框架
  3. 微服务的入门级为框架
二、项目属性配置
  1. 服务属性:
server.port=8081
server.context-path=/girl
  1. @Value:
获取配置文件(application.properties)中的参数组值
  1. @component:
支持自动装配(@Autowired)
  1. @ConfigurationProperties
将对象与配置文件匹配
package com.boe.version.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@Component
//将该对象“MobileSystem”与前缀为"mobileSystem"的配置相匹配
@ConfigurationProperties(prefix = "mobileSystem")
public class MobileSystem {
private String android;
private String ios;
public String getAndroid() {
return android;
}
public void setAndroid(String android) {
this.android = android;
}
public String getIos() {
return ios;
}
public void setIos(String ios) {
this.ios = ios;
}
}
  1. 多环境配置(开发环境与生产环境配置):
spring.profiles.active=prod

三、数据库操作
@Service:
用于标注业务层组件
@Transactional:
在service类前加上@Transactional,声明这个service所有方法需要事务管理。
@Controller:
用于标注控制层组件(如struts中的action)
@RestController
1. Controller, RestController的共同点
     都是用来表示 spring 某个类的是否可以接收HTTP请求
2.  Controller, RestController的不同点
     @Controller标识一个Spring类是Spring MVC controller处理器
     @RestController:   @RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。
示例如下:
  1. @Controller  
  2. @ResponseBody  
  3. public class MyController { }  
  4.   
  5. @RestController  
  6. public class MyRestController { }  
@Repository:
用于标注数据访问组件,即DAO组件
@Component:
支持自动装配(@Autowired)
把普通pojo实例化到spring容器中,相当于配置文件中的

四、AOP
AOP的核心思想:将通用逻辑从业务逻辑中分离出来。
pom依赖包:
org.springframework.boot
spring-boot-starter-aop

以打印日志为例:
package com.boe.version.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;

/**
*Created by SuperChen
*2017年5月1日
*HttpAspect.java
*version
**/
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.boe.version.controller.VersionController.*(..))")
public void log(){
}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
//url
logger.info("RequestURL->{}",request.getRequestURL());
//method
logger.info("HttpMethod->{}",request.getMethod());
//ip
logger.info("IP->{}",request.getRemoteAddr());
//类方法
logger.info("Class_Name->{}",joinPoint.getSignature().getClass()+"."+joinPoint.getSignature().getName());
//参数
logger.info("args->{}",joinPoint.getArgs());
}
@After("log()")
public void doAfter(){
logger.info("Http 请求处理之后");
}
@AfterReturning(returning="object",pointcut="log()")
public void doAfterReturing(Object object){
logger.info("ResponseContent->{}",object.toString());
}
}

五、统一异常处理
  1. 固定返回结果格式
package com.boe.version.utils;
/**
*Created by SuperChen
*00004840
*2017年5月1日 下午12:11:59
**/
public class Result {
//状态码
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;
}

}

  1. 创建自定义的异常类
package com.boe.version.exception;

import com.boe.version.enums.ResultEnum;

/**
*Created by SuperChen
*2017年5月1日
*VersionException.java
*version
**/
public class VersionException extends RuntimeException {
private Integer code;
public VersionException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code=resultEnum.getCode();
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}
}

  1. 捕获异常类
@ ControllerAdvice
@ExceptionHandler
@ResponseBody
package com.boe.version.exception;

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.boe.version.utils.Result;
import com.boe.version.utils.ResultUtil;
/**
*Created by SuperChen
*00004840
*2017年5月1日 下午12:59:39
**/
@ControllerAdvice
public class ExceptionHandle {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof VersionException) {
VersionException versionException = (VersionException) e;
return ResultUtil.error(versionException.getCode(), versionException.getMessage());
}else {
logger.error("msg->{}", "未知错误");
return ResultUtil.error(-1, "未知错误");
}
}

}

  1. 创建枚举——“enum”,统一管理code和msg
package com.boe.version.enums;

/**
*Created by SuperChen
*00004840
*2017年5月1日 下午4:57:22
**/
public enum ResultEnum {
SUCCESS(0,"成功!"),
UNKNOWN_ERROR(-1,"未知错误!"),
IOS_ERROR(101,"IOS 需要小写!"),
ANDROID_ERROR(102,"Android 需要小写!"),
;
private Integer code;
private String msg;
private ResultEnum(Integer code,String msg) {
this.code = code;
this.msg = msg;
}

public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}

}

六、单元测试
pom配置依赖包:
org.springframework.boot
spring-boot-starter-test
test
示例代码:
1. service层:
package com.boe.version.service;

import static 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;

import com.boe.version.entity.Version;

/**
*Created by SuperChen
*00004840
*2017年5月1日 下午6:13:18
**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class VersionServiceTest {
@Autowired
private VersionService versionService;

@Test
public void findOneTest() throws Exception{
Version version = versionService.findOne(1);
assertEquals("1.0.0", version.getVersionNo());
}

}
2. controller层:
package com.boe.version.controller;

import static org.junit.Assert.*;

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;

/**
*Created by SuperChen
*00004840
*2017年5月1日 下午6:31:51
**/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class VersionControllerTest {
@Autowired
private MockMvc mvc;

@Test
public void listTest() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/list"))
.andExpect(MockMvcResultMatchers.status().isOk());
}

}






你可能感兴趣的:(SpringBoot,Spring,注解,框架,java,Java框架)