周末挤出了一些时间,学了点东西,总结了一下,可能还有自己理解不到位的地方,希望大家一起交流学习,好东西要大家一起分享嘛~。时间有点紧张,所以样式没有来及做很好的调整,大家就凑活着看吧。

Spring Boot特点:

  1. 化繁为简,简化配置;
  2. 备受关注,是下一代框架;
  3. 微服务的入门级微框架(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之旅。

生成的项目工程也就如下图所示:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven

项目名称为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项目的方式:

在项目目录下启动命令提示符,输入命令mvn 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配置的是一个高一点年龄小一点的女生)

springMVC 改 springBOOT 难吗 springmvc升级为springboot_jar_02

而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;
}

结果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_spring_03

如果url传参采用传统的方式的话,代码如下:

@RequestMapping(value={"/hi"}, method = RequestMethod.GET)
public String say1(@RequestParam("id") Integer myid) {
    return "id:"+myid;
}

请求结果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven_04

如果不希望传入的参数为空,可以设置这个参数是否为必传,为空可以给它一个默认值

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

测试结果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_jar_05

如果觉得@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();
    }
}

测试结果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_spring_06

使用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);
}
测试结

果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven_07

根据ID查询对象

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

测试结果:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven_08

修改采用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);
    }

测试结果:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_jar_09

删除操作采用DELETE的请求方式,代码如下:

@DeleteMapping("/girls/{id}")
public void girlDel(@PathVariable("id") Integer id) {
    girlRepository.delete(id);
}

测试结果:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven_10

扩展:如果我们想要通过年龄来查询女生呢?

首先扩展我们的GirlRepository接口
public List<Girl> findByAge(Integer age);
接着我们就可以在GirlController中直接使用了。
@GetMapping("/girls/age/{age}")
public List<Girl> girlListByAge(@PathVariable("age") Integer age) {
    return girlRepository.findByAge(age);
}

查询结果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven_11

最后我们来看一下事物的管理:(同时成功或者同时不成功)

(注:使用@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();
}

测试结果如下:

springMVC 改 springBOOT 难吗 springmvc升级为springboot_spring_12

springMVC 改 springBOOT 难吗 springmvc升级为springboot_maven_13

操作成功

以上内容仅代表小白个人在程序猿学习工作道路上的知识总结,如有错误和理解不到位的地方,欢迎各位读者批评斧正,给出宝贵意见,小白将万分感谢。