Spring Boot(spring mvc升级版)
周末挤出了一些时间,学了点东西,总结了一下,可能还有自己理解不到位的地方,希望大家一起交流学习,好东西要大家一起分享嘛~。时间有点紧张,所以样式没有来及做很好的调整,大家就凑活着看吧。
Spring Boot特点:
- 化繁为简,简化配置;
- 备受关注,是下一代框架;
- 微服务的入门级微框架(SpringCloud)。
这里我们采用的开发工具为IDEA
开发环境为1.8,maven版本为3.3.3
首先我们修改一下maven库地址,修改为阿里云的maven库(为了提高下载效率):
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>nexus aliyun.</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
<mirror>
<id>maven.net.cn</id>
<mirrorOf>central</mirrorOf>
<name>central mirror in china</name>
<url>http://maven.net.cn/content/groups/public</url>
</mirror>
然后要使用IDEA创建一个项目工程(Spring Initlalizr)
配置JDK1.8为工程环境,Initializr Service URL为默认的https://start.spring.io
进入选择Spring组件的界面,这里我们只选择web组件即可,生成项目,删去多余的生成文件开启我们的Spring Boot之旅。
生成的项目工程也就如下图所示:

项目名称为girl,假设我们就写一个小女孩。现在写个能访问到的小栗子:
package com.girl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by xiaobai on 2016/12/17.
*/
@RestController
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET )
public String say() {
return "Hello Spring Boot!";
}
}
通过访问localhost:8080/hello就可以访问到这个方法了。
第二种启动maven项目的方式:
在项目目录下启动命令提示符,输入命令maven spring-root:run (前提是配置了maven的环境变量,这里对如何配置maven环境变量不做记录)
第三种启动maven项目的方式:
先编译maven install,在target目录下多了一个.jar形式的文件。可以直接java -jar demo-0.0.1-SNAPSHOT.jar来执行这个jar包。
属性配置
修改application.properties配置文件
server.port=80
server.context-path=/girl
通过http://localhost/girl/hello这个地址来访问。
但这里推荐大家使用.yml形式的文件为配置文件(简便)
server:
port: 80
context-path: /girl
两段代码进行对比大家就能显而易见的看到差别了。(注:yml语法在:后必须有一个空格,否则不支持)
配置中增加这个女孩子的身高信息(不需要管类型,它的类型就是java类中承载类型)
height: 180
我们如何在java类中获取这些配置信息呢?如下:
@Value("${height}")
private String height;
配置中也可以去调用配置属性的值,例如:
server:
port: 80
context-path: /girl
age: 22
height: 180
content: "age:${age}, height:${height}"
配置也可以以面向对象的形式来编写:
girl:
age: 22
height: 180
承载对象类
package com.girl;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by Administrator on 2016/12/17.
*/
/*注入配置注解*/
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private Integer age;
private String height;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}
注入调用:
package com.girl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by xiaobai on 2016/12/17.
*/
@RestController
public class HelloController {
@Value("${height}")
private String height;
@Value("${age}")
private Integer age;
@Value("${content}")
private String content;
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/hello", method = RequestMethod.GET )
public String say() {
return girlProperties.getHeight();
}
}
配置模板(三个配置low配置了一个矮一点但是年纪大一点的女生,top配置的是一个高一点年龄小一点的女生)

而application.yml就可以去配置你今晚准备和那个女生约会,如下:
#项目启动时使用top这个配置
spring:
profiles:
active: low
例子虽然有点猥琐,但是这就好比我们的开发环境和正式环境一样,有的时候系统都不一样,存储文件的位置配置肯定也不一样。这样做的话,可以省去很多修改配置的时间和精力。
命令提示符下我们还可以根据需要来启动不同配置的
先用maven编译:mvn -install
java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=low
下面我们来看看这三个最常用的注解
@RestController:Spring4之后新加的注解,原来返回json需要(@ResponseBody+@Controller)
@RequestMapping:配置url映射
将@RestController改成@Controller报500的错误,需要有页面来承载,先在pom.xml文件中加入spring的官方模版引擎
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在resource的templates文件下新建一个index.html文件,控制器方法中对应的返回“index”字符串即可。
由于为了性能,我们采用的形式都是前后端分离的形式,所以这块了解即可。
@RequestMapping()可以为类或者方法设定请求地址和请求参数,可以设置多个请求地址。例如:
@RequestMapping(value = {"/hello", "/hi"}, method = RequestMethod.GET)
访问localhost/girl/say/hello这个地址即可,如果采用POST方式请求的话,可以使用谷歌浏览器的postman插件来进行测试。
不写请求方式的话,两种方式都能请求到,但是不推荐这样使用。
还可以带参数进行请求
@RequestMapping(value = {"/{id}/hello"}, method = RequestMethod.GET)
public String say(@PathVariable("id")Integer id) {
return "id:"+id;
}
结果如下:

如果url传参采用传统的方式的话,代码如下:
@RequestMapping(value={"/hi"}, method = RequestMethod.GET)
public String say1(@RequestParam("id") Integer myid) {
return "id:"+myid;
}
请求结果如下:

如果不希望传入的参数为空,可以设置这个参数是否为必传,为空可以给它一个默认值
@RequestMapping(value={"/hi"}, method = RequestMethod.GET)
public String say1(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid) {
return "id:"+myid;
}
测试结果如下:

如果觉得@RequestMapping比较繁琐,可以使用@GetMapping和@PostMapping来替代
下面是数据库部分,我们采用Spring-Data-Jpa这个组件来连接MySQL数据库演示。
JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实行这一规范的产品有hibernate和TopLink等。
Spring-Data-Jpa为Spring对hibernate的整合。
首先在pom文件中添加Spring-Date-Jpa和MySQL连接数据库的支持。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
其次在yml文件中写相关配置
#这里我们使用top这个配置
spring:
profiles:
active: low
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: root
jpa:
hibernate:
ddl-auto: create
show-sql: true
写一个Java Bean,测试是否能够生成对应的数据库。
先编写一个接口GirlRepository继承JpaRepository
public interface GirlRepository extends JpaRepository<Girl, Integer>{}
再编写一个Controller
@RestController
public class GirlController {
@Autowired
private GirlRepository girlRepository;
@GetMapping(value = "/girls")
public List<Girl> girlList() {
return girlRepository.findAll();
}
}
测试结果如下:

使用Post形式模拟添加一个女生信息
@PostMapping("/girls")
public Girl girlAdd(@RequestParam("height") String height,
@RequestParam("age") Integer age) {
Girl girl = new Girl();
girl.setAge(age);
girl.setHeight(height);
return girlRepository.save(girl);
}
测试结果如下:

根据ID查询对象
@GetMapping("/girls/{id}")
public Girl girlFindOne(@PathVariable("id") Integer id) {
return girlRepository.findOne(id);
}
测试结果:

修改采用PUT请求形式,代码如下:
@PutMapping("/girls/{id}")
public Girl girlUpdate(@PathVariable("id") Integer id,
@RequestParam("height") String height,
@RequestParam("age") Integer age) {
Girl girl = new Girl();
girl.setId(id);
girl.setHeight(height);
// girl.setAge();
return girlRepository.save(girl);
}
测试结果:

删除操作采用DELETE的请求方式,代码如下:
@DeleteMapping("/girls/{id}")
public void girlDel(@PathVariable("id") Integer id) {
girlRepository.delete(id);
}
测试结果:

扩展:如果我们想要通过年龄来查询女生呢?
首先扩展我们的GirlRepository接口
public List<Girl> findByAge(Integer age);
接着我们就可以在GirlController中直接使用了。
@GetMapping("/girls/age/{age}")
public List<Girl> girlListByAge(@PathVariable("age") Integer age) {
return girlRepository.findByAge(age);
}
查询结果如下:

最后我们来看一下事物的管理:(同时成功或者同时不成功)
(注:使用@Autowired要在被引入类前加组件标签@Component )
新建一个GirlService类。
@Component
public class GirlService {
@Autowired
private GirlRepository girlRepository;
/**
* JPA事务的管理
*/
public void insertTwo() {
Girl girlA = new Girl();
girlA.setHeight("175");
girlA.setAge(20);
girlRepository.save(girlA);
Girl girlB = new Girl();
girlB.setHeight("160");
girlB.setAge(18);
girlRepository.save(girlB);
}
}
在GirlController中调用:
@Autowired
private GirlService girlService;
@PostMapping("/girls/two")
public void girlTwo() {
girlService.insertTwo();
}
测试结果如下:


操作成功
Spring Boot(spring mvc升级版)的更多相关文章
- Spring boot +Spring Security + Thymeleaf 认证失败返回错误信息
[Please make sure to select the branch corresponding to the version of Thymeleaf you are using] Stat ...
- spring Boot+spring Cloud实现微服务详细教程第二篇
上一篇文章已经说明了一下,关于spring boot创建maven项目的简单步骤,相信很多熟悉Maven+Eclipse作为开发常用工具的朋友们都一目了然,这篇文章主要讲解一下,构建spring bo ...
- spring Boot+spring Cloud实现微服务详细教程第一篇
前些天项目组的大佬跟我聊,说项目组想从之前的架构上剥离出来公用的模块做微服务的开发,恰好去年的5/6月份在上家公司学习了国内开源的dubbo+zookeeper实现的微服务的架构.自己平时对微服务的设 ...
- 255.Spring Boot+Spring Security:使用md5加密
说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)h ...
- 256.Spring Boot+Spring Security: MD5是加密算法吗?
说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)h ...
- Spring Boot+Spring Security:获取用户信息和session并发控制
说明 (1)JDK版本:1.8(2)Spring Boot 2.0.6(3)Spring Security 5.0.9(4)Spring Data JPA 2.0.11.RELEASE(5)hiber ...
- Cola Cloud 基于 Spring Boot, Spring Cloud 构建微服务架构企业级开发平台
Cola Cloud 基于 Spring Boot, Spring Cloud 构建微服务架构企业级开发平台: https://gitee.com/leecho/cola-cloud
- spring boot + spring batch 读数据库文件写入文本文件&读文本文件写入数据库
好久没有写博客,换了一家新公司,原来的公司用的是spring,现在这家公司用的是spring boot.然后,项目组布置了一个任务,关于两个数据库之间的表同步,我首先想到的就是spring batch ...
- Spring Boot/Spring Cloud、ESB、Dubbo
如何使用Spring Boot/Spring Cloud 实现微服务应用spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中的配置管理.服务发现. ...
- 使用Spring Boot,Spring Cloud和Docker实现微服务架构
https://github.com/sqshq/PiggyMetrics Microservice Architecture with Spring Boot, Spring Cloud a ...
随机推荐
- POJ2584 T-Shirt Gumbo 二分图匹配(网络流)
#include <cstdio> #include <cstring> #include <algorithm> const int inf=0x3f3f3f3f ...
- 主成份分析PCA
Data Mining 主成分分析PCA 降维的必要性 1.多重共线性--预测变量之间相互关联.多重共线性会导致解空间的不稳定,从而可能导致结果的不连贯. 2.高维空间本身具有稀疏性.一维正态分布有6 ...
- 我用Emacs,后来转向Vim——Vim学习之Vim键盘图(绝对值得珍藏)
Emacs本来就比较臃肿,麻烦.当我发现Vim键盘图时,我就渐渐转向Vim,追随Unix/Linux哲学去了.. 我用了Emacs三个月,因为它的学习曲线没Vim陡,这点吸引了,我使用Linux才7. ...
- 《find技巧》-“linux命令五分系列”之一
一天一个命令,做个记录, 我要成大神,哈哈哈 本原创文章属于<Linux大棚>博客. 博客地址为http://roclinux.cn. 文章作者为roc 希望您能通过捐款的方式支持Linu ...
- ios开发之UIImageView
废话少说,直接进入正题!!! 1.创建一个UIImageView: 创建一个UIImageView对象的几种方法: UIImageView *imageView1 = [[UIImageView al ...
- bootstrap学习--模态弹出框modals轮子
1.点击按钮型 <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"> ...
- [开源]jquery-ajax-cache:快速优化页面ajax请求,使用localStorage缓存请求
项目:jquery-ajax-cache 地址:https://github.com/WQTeam/jquery-ajax-cache 最近在项目中用到了本地缓存localStorage做数据 ...
- curl http_code状态码 含义
curl爬取过程中,会返回一个http_code,下面是他们的意义信息 $http_code["]="Unable to access"; $http_code[&quo ...
- js打开新的窗体不被浏览器阻止
转载自js弹出新窗口而不会被浏览器阻止的方法有时候希望可以用js另开新窗口,但用window.open方法打开窗口总是被浏览器阻止, 可以用下面的方法打开新窗口而不会遭到拦截 1.新添加一个Form ...
- Python学习的一些好资料
教程: 1. 廖雪峰的Python教程:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a0 ...