SpringBoot初識


SpringBoot特點

SpringBoot可以說是Spring MVC的升級版,化繁為簡,簡化配置,讓很復雜的一些操作變得簡便,SpringBoot也逐漸成為下一代框架。它也是微服務的入門級框架,Spring為微服務架構提供了一整套組件,統稱為SpringCloud,而SpringCloud是建立在SpringBoot基礎之上的。

項目搭建

  • IDE:idea
  • jdk:1.8
  • Maven:3.3.9

創建好項目以后,把.mvn文件夾,mvnw和mvnw.cmd文件刪除,第一次創建項目target文件夾是沒有的,以后會自動生成。

運行啟動類

tomcat服務已打開,端口為8080.

新建類Helloworld

package com.zzh.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2017/4/8.
 */
@RestController
public class HelloWorld {

    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public String say() {
        return "This is SpringBoot! ";
    }
}

重新啟動

屬性配置

為了達到簡便,將resources下的application.properties刪除,自己創建一個application.yml

新建類GirlProperties

里面的 @ConfigurationProperties(prefix = "girl")即獲取前綴是girl的配置,也就是會將上面application.yml中出現girl的兩個屬性值,映射到這里。
還要注意添加 @Component注解,這樣在其他類里使用 @Autowired才能注入成功。

package com.zzh.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


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

HelloWorld類輸出配置中的屬性

package com.zzh.controller;

import com.zzh.properties.GirlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2017/4/8.
 */
@RestController
public class HelloWorld {

    @Autowired
    private GirlProperties girlProperties;

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

多環境配置

不同的環境可以設置不同的屬性值,也就不需要每次修改都要改動yml總文件了。

通過在application.yml中spring.profiles.active使用不同的配置(比如dev或者prod)。

@RestController與 @Controller的區別

如果將上面HelloWorld類上的RestController注解換成Controller注解后會怎么樣呢,啟動時不會有什么錯誤,但是當我打開網頁后,頁面就不能正常顯示了。那是因為之前用的RestController注解,它是Spring4之后新加的注解,原來返回json需要 @ResponseBody配合 @Controller,所以相當於 @Controller和 @ResponseBody的組合。

@RequestMapping注解

這個注解跟Spring MVC中差別不到,如果需要不同的地址都可以訪問到這個方法,直接在value = {"/helloworld,"/hi"}寫成集合形式就可以。

URL參數處理

  • @PathVariable獲取url中的數據
package com.zzh.controller;

import com.zzh.properties.GirlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/helloworld")
public class HelloWorld {

    @Autowired
    private GirlProperties girlProperties;

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

可以看到url上的待傳參數與PathVariable中的值相同,而后面的形參可以隨意設置。

  • @RequestParam獲取請求參數的值

這個注解可以為參數設置默認值,如果當用戶選擇不傳入值而沒有設置默認值時,系統會給自動賦為null。

@RequestMapping(value = "/talk" , method = RequestMethod.GET)//等同於@GetMapping(value="/talk")
    public String talk(@RequestParam(value = "id",required = false,defaultValue = "0") Integer myId) {
        return "id: " + myId;
    }

required=false表示不必傳值,defaultValue即為默認值。

  • @GetMapping組合注解

即 @RequestMapping(value = "/talk" , method = RequestMethod.GET)等同於 @GetMapping(value="/talk"),相應的也有 @PostMapping等等。

數據庫操作

  • 添加pom依賴
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
  • Spring-Data-Jpa

JPA(Java Persistence API)定義了一系列對象持久化標准,實現這一規范的產品有Hibernate,TopLink等。

  • 添加數據庫和jpa相應配置

在application.yml中添加:

創建數據庫一個數據庫,編碼選擇utf8mb4。

  • 添加實體

數據庫中現在並沒有表,我們也不需要自己寫sql去創建,只要創建相應的實體類就可以映射到數據庫中。

package com.zzh.domain;


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;

    public Girl() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

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

}

重新啟動之后就會發現數據庫中有表了。

  • 創建操作數據庫接口GirlRepository並繼承JpaRepository
package com.zzh.repository;

import com.zzh.domain.Girl;
import org.springframework.data.jpa.repository.JpaRepository;


public interface GirlRepository extends JpaRepository<Girl,Integer>{

}

查詢女生列表

創建GirlController類:

通過idea自帶的REST Client進行測試,查詢成功並返回了結果。

添加一個女生

注意:測試的時候需要給出參數

得到剛才添加的返回結果

通過id查詢一個女生

測試返回該女生:

通過id更新一個女生

更新有兩種方法,一種就是new一個對象去替換原有的對象,還有一種就是被我注釋了的,先通過ID查詢到那個女生,然后修改里面的數據。

這里將3號女生的cupSize改為F:

通過id刪除女生

通過age來查詢

之前都是通過id來查詢,現在要通過年齡來查詢,只要擴展一下GirlRepository接口即可。接口里面的方法名是有規定的,不能亂寫。

在數據庫中多存入一條18歲的信息進行查詢


事務管理

現在需要同時插入兩個女生,兩者要么同時成功,要么同時失敗,先按正常的套路來先設計一個Service類, @Transactional注解也暫時不加,把數據庫中cupSize字段的長度改為1,然后故意在下面插入操作中,將girlA的cupSize設置為一個錯誤的數進行插入,因為正確的girlB先執行插入,所以girlB插入成功了,而girlA字段有錯則插入不成功。這時違背了預先設定的同時成功同時失敗准則,所以需要在這個方法上加上 @Transactional注解。

package com.zzh.service;

import com.zzh.domain.Girl;
import com.zzh.repository.GirlRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class GirlService {

    @Autowired
    private GirlRepository girlRepository;

    @Transactional
    public void insertTwo() {
        /**
         * 如果沒有事務注解
         * 正確的girlB放在girlA前面
         * 數據庫還是會存儲girlB的信息
         */
        Girl girlB = new Girl();
        girlB.setCupSize("G");
        girlB.setAge(19);
        girlRepository.save(girlB);

        Girl girlA = new Girl();
        girlA.setCupSize("DDDD");
        girlA.setAge(18);
        girlRepository.save(girlA);

    }
}

測試后發現都沒有插入成功,事務發揮了作用。


總結

這篇文章簡單介紹了一些springBoot配置方面的事情,同時也介紹了部分主要的SpringBoot的注解,最主要的還是介紹了數據庫的相關操作,通過使用spring-data-Jpa來實現對數據庫的增刪改查。下一篇文章將會進一步講解springBoot表單驗證和AOP異常處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM