SpringBoot 快速入門筆記

一、環(huán)境準備

配置好 java, maven , 并給 maven 設(shè)置國內(nèi)鏡像(阿里)

在 maven 安裝目錄/conf 下,找到 settings.xml,配置如下代碼

<mirrors>
    <mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>        
    </mirror>
</mirrors>

編輯器: IDEA

二、用 IDEA 創(chuàng)建項目

打開 IDEA 新建項目,選擇 Spring Initializr ,勾選 Web 依賴。

三、啟動 SpringBoot 項目的三種方式

  1. IDEA 啟動

在 IDEA 中,找到有 @SpringBootApplication 注解的類,右鍵,run xxxApplication

或點擊 IDEA 中的快捷按鈕

  1. maven命令直接啟動

    命令行進入項目目錄,執(zhí)行命令:
    mvn spring-boot:run
    
  2. maven命令先編譯成 jar 再啟動

    命令行進入項目目錄,先編譯程序執(zhí)行:
    
    mvn install
    
    然后 
    
    cd target
    
    進入生成的 target 目錄,看到 test-0.0.1-SNAPSHOT.jar
    
    java -jar test-0.0.1-SNAPSHOT.jar
    

四、SpringBoot 配置

4.1 兩種配置文件

SpringBoot 的配置文件有兩種:

application.propertiesapplication.yml

兩種文件效果一樣,只是寫法不同。

application.properties 文件配置:

server.port=8080
server.servlet.context-path=/test

application.yml文件配置

server:
  port: 8081
  servlet:
    context-path: /test

注意:冒號后面必須加個空格,不能寫成port:8081,需要在 port: 和 8081 之間加空格

對比來看 application.yml 文件寫法更精簡,建議使用。

4.2 屬性配置

可在application.yml 配置文件里自定義配置信息并在項目中讀取。

4.2.1 單個屬性讀取

配置信息 cupSizeage

server:
  port: 8081
cupSize: B
age: 20

在 Controller 中讀取

@RestController
public class HelloController {

    @Value("${cupSize}")
    private String cupSize;

    @Value("${age}")
    private Integer age;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say(){
        return cupSize + age;
    }
}

在 Controller 中通過 @Value("${age}") 注解讀取配置文件中的屬性

4.2.2 通過對象多屬性一起讀取

application.yml

server:
  port: 8081

girl:
  cupSize: B
  age: 20

新建類 GirlProperties.java

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

Controller 中使用

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girl;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say(){
        return girl.getCupSize() + girl.getAge();
    }
}

4.2.3 多環(huán)境配置

配置開發(fā)環(huán)境和生產(chǎn)環(huán)境

新建 application-dev.yml 作為開發(fā)環(huán)境配置

server:
  port: 8082

girl:
  cupSize: F
  age: 24

新建 application-prod.yml 作為生產(chǎn)環(huán)境配置

server:
  port: 8081

girl:
  cupSize: B
  age: 20

修改 application.yml , 配置為開發(fā)環(huán)境

spring:
  profiles:
    active: dev

如需配置為生產(chǎn)環(huán)境,將 active: dev 改為 active: prod

spring:
  profiles:
    active: prod

五、Controller 的使用

注解 說明
@Controller 處理 http 請求
@RestController Spring4 之后新加的注解,原來返回 json 需要 @ResponseBody 配合 @Controller
@RequestMapping 配置 url 映射
@PathVariable 獲取 url 中的數(shù)據(jù)
@RequestParam 獲取請求參數(shù)的值
@GetMapping 組合注解

5.1 @RestController

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girl;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say(){
        return girl.getCupSize() + girl.getAge();
    }
}

注:同時使用 @ResponseBody 和 @Controller 與單獨使用 @RestController 效果相同

5.2 @RequestMapping

5.2.1 給方法配置多個訪問路徑

給 value 配置多個路徑的集合

@RequestMapping(value = {"/happy", "/hi"}, method = RequestMethod.GET)
public String sayHi(){
    return "happy or Hi";
}

訪問 http://localhost:8082/hi 或者 http://localhost:8082/happy 均可進入方法 sayHi()

5.2.2 給類配置訪問路徑

@RestController
@RequestMapping(value = "/girl")
public class HelloController {

    @RequestMapping(value = {"/happy", "/hi"}, method = RequestMethod.GET)
    public String sayHi(){
        return "happy or Hi";
    }
    
}

需要訪問 http://localhost:8082/girl/hi

5.3 @PathVariable

@PathVariable 用來獲取 url 中的參數(shù)

 @RequestMapping(value = "/go/{id}", method = RequestMethod.GET)
 public String go(@PathVariable("id") String id){
    return "id: " + id;
 }

訪問地址 http://localhost:8082/girl/go/123

id 也可以放前面,效果一樣

@RequestMapping(value = "/{id}/go", method = RequestMethod.GET)
public String go(@PathVariable("id") String id){
    return "id: " + id;
}

5.4 @RequstParam

獲取請求參數(shù)的值

@RequestMapping(value = "/hei", method = RequestMethod.GET)
public String getRequestParam(@RequestParam("id") String id){
    return "id: " + id;
}

訪問地址:http://localhost:8082/girl/hei?id=123

給參數(shù)加默認值

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

id 不傳時默認是 0。

5.5 @GetMapping

 @GetMapping(value = "/hei")
 public String getRequestParam(@RequestParam(value = "id", required = false, defaultValue = "0")        String id){
    return "id: " + id;
}

簡化 @RequestMapping 的寫法,還有 @PostMapping 等。

六、數(shù)據(jù)庫操作 JPA

JPA (Java Persistence API) 定義了一系列的對象持久化的標準,目前實現(xiàn)這一規(guī)范的產(chǎn)品有 Hibernate、TopLink等。

6.1 配置引入 MySQL 和 JPA

修改 pom.xml 文件添加 JPAMySQL 依賴

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

修改 application.yml 文件,配置 JPAMySQL

spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://0.0.0.0:3306/dbgirl
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

注:url 中最后的 dbgirl 是你的數(shù)據(jù)庫名字

ddl-auto 可選參數(shù)有五種:

create 啟動時刪數(shù)據(jù)庫中的表,然后創(chuàng)建,退出時不刪除數(shù)據(jù)表

create-drop 啟動時刪數(shù)據(jù)庫中的表,然后創(chuàng)建,退出時刪除數(shù)據(jù)表 如果表不存在報錯

update 如果啟動時表格式不一致則更新表,原有數(shù)據(jù)保留

none 不進行配置

validate 項目啟動表結(jié)構(gòu)進行校驗 如果不一致則報錯

6.2 創(chuàng)建數(shù)據(jù)庫和表

創(chuàng)建數(shù)據(jù)庫 dbgirl ,建數(shù)據(jù)庫時編碼應(yīng)選用 utf-8 utf8mb4,以便能存儲表情符號等。

然后在項目中新建 java 類Girl

package com.solo.test01;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;

    private String cupSize;

    private Integer age;
    
    //需要有空參構(gòu)造函數(shù)
    public Girl() {
    }
    
    //getter, setter 方法省略
}

運行項目,數(shù)據(jù)庫會自動創(chuàng)建表 girl

6.3 增刪改查

創(chuàng)建 java 類 GirlRepository

package com.solo.test01.girl;

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface GirlRepository extends JpaRepository<Girl, Integer> {
    List<Girl> findAllByAge(Integer age);
}

創(chuàng)建 Controller 類 GirlController

package com.solo.test01.girl;

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

import java.util.List;

@RestController
public class GirlController {

    @Autowired
    private GirlRepository repository;

    /**
     * 查詢所有女生
     *
     * @return
     */
    @GetMapping(value = "/girls")
    public List<Girl> getAll() {
        return repository.findAll();
    }

    /**
     * 添加一位女生
     *
     * @param cupSize
     * @param age
     * @return 返回新添加的對象
     */
    @PostMapping(value = "/girl/add")
    public Girl add(@RequestParam("cupSize") String cupSize,
                    @RequestParam("age") Integer age) {

        Girl girl = new Girl();
        girl.setAge(age);
        girl.setCupSize(cupSize);

        return repository.save(girl);
    }

    /**
     * 更新
     *
     * @param id
     * @param cupSize
     * @param age
     * @return
     */
    @PutMapping(value = "/girls/{id}")
    public Girl update(@PathVariable("id") Integer id,
                       @RequestParam("cupSize") String cupSize,
                       @RequestParam("age") Integer age) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);

        return repository.save(girl);
    }

    /**
     * 通過id查詢一個女生
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/girls/{id}")
    public Girl findOne(@PathVariable("id") Integer id) {
        return repository.findById(id).get();
    }

    /**
     * 刪除
     *
     * @param id
     */
    @DeleteMapping(value = "/girls/{id}")
    public void deleteById(@PathVariable("id") Integer id) {
        repository.deleteById(id);
    }

    /**
     * 通過年齡查
     *
     * @param age
     * @return
     */
    @GetMapping(value = "/girls/age/{age}")
    public List<Girl> findByAge(@PathVariable("age") Integer age) {
        return repository.findAllByAge(age);
    }
}

以上通過 JPA 完成了增刪改查。


作者正在寫一個有趣的開源項目 coderiver,致力于打造全平臺型全棧精品開源項目。

coderiver 中文名 河碼,是一個為程序員和設(shè)計師提供項目協(xié)作的平臺。無論你是前端、后端、移動端開發(fā)人員,或是設(shè)計師、產(chǎn)品經(jīng)理,都可以在平臺上發(fā)布項目,與志同道合的小伙伴一起協(xié)作完成項目。

coderiver 河碼 類似程序員客棧,但主要目的是方便各細分領(lǐng)域人才之間技術(shù)交流,共同成長,多人協(xié)作完成項目。暫不涉及金錢交易。

計劃做成包含 pc端(Vue、React)、移動H5(Vue、React)、ReactNative混合開發(fā)、Android原生、微信小程序、java后端的全平臺型全棧項目,歡迎關(guān)注。

項目地址:https://github.com/cachecats/coderiver

您的鼓勵是我前行最大的動力,歡迎點贊,歡迎送小星星? ~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評論 6 342
  • 個人專題目錄[http://www.itdecent.cn/u/2a55010e3a04] 一、Spring B...
    Java及SpringBoot閱讀 2,892評論 1 25
  • Spring Data Jpa 簡介 JPA JPA(Java Persistence API)意即Java持久化...
    fulgens閱讀 239,394評論 12 170
  • 無意中收拾了衣柜,一下子神清氣爽,內(nèi)心充盈得想要飛起來 平時的生活真是很粗糙,衣柜已經(jīng)半年沒有整理了。 今年早春的...
    南杏18閱讀 328評論 0 0

友情鏈接更多精彩內(nèi)容