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); }
2小时学会spring boot 以及spring boot进阶之web进阶(已完成)的更多相关文章
- spring boot / cloud (十五) 分布式调度中心进阶
spring boot / cloud (十五) 分布式调度中心进阶 在<spring boot / cloud (十) 使用quartz搭建调度中心>这篇文章中介绍了如何在spring ...
- spring boot / cloud (十二) 异常统一处理进阶
spring boot / cloud (十二) 异常统一处理进阶 前言 在spring boot / cloud (二) 规范响应格式以及统一异常处理这篇博客中已经提到了使用@ExceptionHa ...
- 一:Spring Boot、Spring Cloud
上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...
- Spring Kafka和Spring Boot整合实现消息发送与消费简单案例
本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...
- 使用Spring Session实现Spring Boot水平扩展
小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...
- 一起来学spring Cloud | 第一章:spring Cloud 与Spring Boot
目前大家都在说微服务,其实微服务不是一个名字,是一个架构的概念,大家现在使用的基于RPC框架(dubbo.thrift等)架构其实也能算作一种微服务架构. 目前越来越多的公司开始使用微服务架构,所以在 ...
- Spring,Spring MVC及Spring Boot区别
什么是Spring?它解决了什么问题? 我们说到Spring,一般指代的是Spring Framework,它是一个开源的应用程序框架,提供了一个简易的开发方式,通过这种开发方式,将避免那些可能致使代 ...
- 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践
由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...
- Spring Cloud Alibaba与Spring Boot、Spring Cloud之间不得不说的版本关系
这篇博文是临时增加出来的内容,主要是由于最近连载<Spring Cloud Alibaba基础教程>系列的时候,碰到读者咨询的大量问题中存在一个比较普遍的问题:版本的选择.其实这类问题,在 ...
随机推荐
- Android活动的启动模式
1. standard 标准模式,是活动默认的启动模式,在不进行显示指定的情况下,所有活动都会自动使用这种模式. Android使用返回栈管理活动,在standard模式下,每当启动一个新的活动,它就 ...
- jquery 获取easyui combobox选中的值、赋值
jquery easyui combobox 控件支持单选和多选 1.获取选中的值 $('#comboboxlist').combobox('getValue'); //单选时 $('#combob ...
- openlayers 聚合效果
//cyd var cydclusterSource = new ol.source.Cluster({ distance: 40, source: new ol.source.Vector({ fe ...
- rbac——界面、权限
一.模板继承 知识点: users.html / roles.html 继承自 base.html 页面滚动时,固定 .menu { background-color: bisque; positio ...
- Bootstrap导航栏navbar源码分析
1.本文目地:分析bootstrap导航栏及其响应式的实现方式,提升自身css水平 先贴一个bootstrap的导航栏模板 http://v3.bootcss.com/examples/navbar- ...
- 《CSS实现单行、多行文本溢出显示省略号》
如果实现单行文本的溢出显示省略号同学们应该都知道用text-overflow:ellipsis属性来,当然还需要加宽度width属来兼容部分浏览. 实现方式: overflow: hidden; te ...
- javascript实现数据结构:线索二叉树
遍历二叉树是按一定的规则将树中的结点排列成一个线性序列,即是对非线性结构的线性化操作.如何找到遍历过程中动态得到的每个结点的直接前驱和直接后继(第一个和最后一个除外)?如何保存这些信息? 设一棵二叉树 ...
- [PAMI 2018] Differential Geometry in Edge Detection: accurate estimation of position, orientation and curvature
铛铛铛,我的第一篇文章终于上线了,过程曲折,太不容易了--欢迎访问--- https://ieeexplore.ieee.org/document/8382271/ 后面有需要的话可以更新一下介绍,毕 ...
- Myeclipse中进行JUnit单元测试
最近学习了在myeclipse中进行单元测试,写点东西总结总结. JUnit单元测试: 测试对象为一个类中的方法. juint不是javase中的部分,所以必须导入jar包,但是myeclipse自带 ...
- AE多用户同时编辑同一个版本数据的解决方法
项目中做了入库的功能,测试一切正常,但是实际使用多个用户同时编辑default版本的时候,问题就来了,StopEditing 错误信息如下 FDO_E_VERSION_REDEFINED -21472 ...