Spring Boot

SpringBoot的优点

  1. 简化配置
  2. 下一代Java Web框架
  3. 微服务的入门级微框架

课程目录

  1. 开发第一个SpringBoot程序
  2. 自定义属性配置
  3. Controller的使用
  4. spring-data-jpa(用于操作数据库,很方便)
  5. 事务管理(数据库)

结果: 可以开发一个小型的Java Web项目

前置知识:

  1. 利用maven构建项目
  2. Spring注解
  3. RESTful API

注意:

  1. 具备必要的前置知识
  2. 不需要去学习SpringMVC
  3. Java、Maven等版本保持一致

pom.xml配置.

Spring Boot优点: 部署,配置,编码,监控都变得很简单

课程开始

  1. 开发第一个SpringBoot程序 创建SpringBoot工程的两种方式: 1) IDEA(专业版的IDEA,社区版不自带SpringBoot的创建) 2) https://start.spring.io下创建,下载zip包,在IDEA中打开 工程启动的三种方式: (可以直接去Web UI上查看结果) http://localhost:8080 默认页面 http://localhost:8080/hello 写完hello程序的页面 1) 直接IDEA启动 2) 在终端找到项目目录, 运行 mvn spring-boot:run
    3) 进行项目打包, mvn clean package,在 target目录下找到打包文件,用java -jar target/ruby-0.0.1-SNAPSHOT.jar 运行

  2. 配置 (书写以及如何使用) spring.datasource.url: jdbc:mysql://127.0.0.1:3306/ spring.datasource.username: root spring.datasource.password: 123456 spring.datasource.driver-class-name: com.mysql.jdbc

    (使用 .yml 格式的属性, .properties格式的属性 ,前一种可以折叠重复的部分,十分简洁明了,推荐前一种.后一种,它不折叠重复的字段) application.yml

    server:
      port: 8888
      servlet:
        context-path: /ruby
    

屏幕快照 2019-04-11 18.36.13

LimitConfig.class

```
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;

@Component //注入成分
@ConfigurationProperties(prefix = "limit")  // 注入配置,前缀是limit
@Data //注入数据
public class LimitConfig {

    private BigDecimal minMoney;

    private BigDecimal maxMoney;

    private String description;
}
```

小结:

单个配置引入,使用 @Value 多个配置引入,使用 @Component @ConfigurationProperties

多环境的配置。测试环境(dev),生产环境(prod)

Controller的使用

@Controller 处理http请求 @RestController Spring4之后新加的注解,原来返回json需要@ResponseBody配合@Controller @RequestMapping 配置url映射,有些特殊需求,还是需要它的 @GetMapping 直接调用Get请求的方式,配置url映射, spring-boot2.0版本后开始支持

@RequestMapping({"/hello","hi","foo"}) // 访问 hello hi foo 都是一样的 @GetMapping("/say") // 获取say

@GetMapping("/say") // 支持Get请求方式 新版本的写法 2.0往上 @PostMapping("/say") // 支持Post请求方式 @RequestMapping("/say") // 同时支持Get和Post两种方式 要么用Get/Post,只用一种,就不会起冲 注意: 一般选用一种就好,做人要有原则,服务器请求也是. http://localhost:8888/ruby/hi/say

@PathVariable 获取url中的数据 @GetMapping("/say/{id}") sayHello(@RequestParam(value = "id") http://localhost:8888/ruby/hello/say/100 @RequestParam 获取请求参数的值 @GetMapping("/say") http://localhost:8888/ruby/hello/say/?id=100
两者的调用方法不同,书写也不同,注意区分,一般使用 @RequestParam

学会使用@RequestParam注解方法即可

    @GetMapping("/say")
    // 可以只设置id, required和defaultValue可以不设置,但是,一般设置比较好
    public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
    // return "说明: " + limitConfig.getDescription();
        return "id: " + id;
    }

HelloController.class的标准写法

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"/hello","/hi","/foo"}) // 这块可以写成数组,也可以写成单个值.  command+P弹出提示
public class HelloController {

    @Autowired
    private LimitConfig limitConfig;

    @GetMapping("/say") //  新版本的写法 2.0往上
//    @PostMapping("/say")
    public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
//        return "说明: " + limitConfig.getDescription();
        return "id: " + id;
    }
}

postman工具测试http请求的测试方法

屏幕快照 2019-04-11 19.46.26

连接数据库:

在application-dev.yml中添加mysql配置信息

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ruby?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

Notes: 链接数据库时报这个错怎么解决啊 2018-05-22 21:27:04.985 ERROR 7960 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization. 要在url中添加时区,不然会报错的.

url: jdbc:mysql://localhost:3306/testOne?serverTimezone=Asia/Shanghai 加编码格式,不然,插入中文数据,会出现错误???

RubyMoney.class

package com.imooc.ruby;

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;

/**
 * 创建ruby_money表,在表中创建id,money,producer,consumer四个字段
 * 注意,这里的id要设置成Long类型,不然会在创建新数据的时候,创建数据失败
 */
@Entity    // 实体
@Table
@Data   // 生成方法
public class RubyMoney {

    @Id                 // 设置主键
    @GeneratedValue     // Id是自增的
    private Integer id;    // Long类型,需要重点注意

    private BigDecimal money;

    /**
     * 发送方
     */
    private String producer;

    /**
     * 接收方
     */
    private String consumer;
}

RubyMoneyRepository.class

package com.imooc.ruby;

import org.springframework.data.jpa.repository.JpaRepository;

/**
 * DAO层
 */
public interface RubyMoneyRepository extends JpaRepository<RubyMoney,Integer> {
}

RubyMoneyController.class

package com.imooc.ruby;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 *
 * Controller层
 */
@RestController
public class RubyMoneyController {

    @Autowired
    private RubyMoneyRepository rubymoneyRepository;

    /**
     * 获取红包列表
     * @return  查询全表
     */
    @GetMapping("/ruby_1")
    // 查询表中所有数据
    public List<RubyMoney> list() {

        return rubymoneyRepository.findAll();
    }

    /**
     * 创建红包
     * @param producer
     * @param money
     * @return
     */
    @PostMapping("/ruby_2")
    // create是不需要主键这一列的,因为主键id设置的是自增
    public RubyMoney create(@RequestParam("producer") String producer,
                            @RequestParam("money")BigDecimal money) {

        RubyMoney rubyMoney = new RubyMoney();
        rubyMoney.setProducer(producer);
        rubyMoney.setMoney(money);
        return rubymoneyRepository.save(rubyMoney);
    }

    /**
     * 通过id查询红包
     * @param id
     * @return
     */
    @GetMapping("/ruby_3/{id}")
    // findById这块是通过主键,进行查询的
    public RubyMoney findById(@PathVariable("id") Integer id) {
        return rubymoneyRepository.findById(id).orElse(null);
    }

    @PutMapping("/ruby_4/{id}")
    // update这块是通过主键,进行更新的
    public RubyMoney update(@PathVariable("id") Integer id,
                            @PathParam("consumer") String consumer) {
        Optional<RubyMoney> optional = rubymoneyRepository.findById(id);
        if (optional.isPresent()) {
            RubyMoney rubyMoney = new RubyMoney();
            rubyMoney.setConsumer(consumer);
            return rubymoneyRepository.save(rubyMoney);
        }
        return null;
    }
}

RubyApplication.class

package com.imooc.ruby;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * 主程序入口
 */
@SpringBootApplication
public class RubyApplication {

    public static void main(String[] args) {
        SpringApplication.run(RubyApplication.class, args);
    }

}

补充: 屏幕快照 2019-04-29 00.59.48

原文地址:https://www.cnblogs.com/suixingc/p/spring-boot-xue-xi.html